1025反转链表
给定一个常数ķ以及一个单链表L,请编写程序将大号中每ķ个结点反转例如:给定大号为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;如果ķ为4,则输出应该为4→3→2→1→5→6,即最后不到ķ个元素不反转。
输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址,结点总个数正整数N(<= 10 ^ 5 ^),以及正整数K(<= N),即要求反转的子链结点的个数。结点的地址是5位非负整数,NULL地址用-1表示。
接下来有Ñ行,每行格式为:
地址数据接下来
其中地址是结点地址,数据是该结点保存的整数数据,下一个是下一结点的地址。
输出格式:
对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。
输入样例:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
输出样例:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
-
思路:使用两个指针模拟链表指针接着转向,第一次没有全部过掉漏看题目是每ķ个进行一次反转,第一次提交只做了一次QAQ;
(画得很迷〜)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct List
{
int next;
int data;
}*Pnode;
main(int argc, char const *argv[])
{
int first_adress,count,k;
scanf("%d%d%d",&first_adress,&count,&k);
Pnode Node=(Pnode)malloc(sizeof(struct List)*10e5);
memset(Node,0,sizeof(struct List)*10e5);
int i;
for(i=0;i<count;i++)
{
int temp;
scanf("%d",&temp);
scanf("%d%d",&Node[temp].data,&Node[temp].next);
}
int adress;
int old=first_adress;
int new=Node[first_adress].next;
// printf("old=%d new=%d\n",old,new);
int temp;
for(i=1;i<k;i++)
{
temp=Node[new].next;
Node[new].next=old;
old=new;
new=temp;
}
Node[first_adress].next=new;
for(adress=old;adress!=-1;adress=Node[adress].next)
{
if(Node[adress].next!=-1)
printf("%05d %d %05d\n",adress,Node[adress].data,Node[adress].next);
else
printf("%05d %d -1\n",adress,Node[adress].data,Node[adress].next);
}
system("pause");
return 0;
}
emmm当然没有ac辣
原因:
- 有无效数据,在算总共需要几次反转时候不能单纯的使用总数除以K,可能会偏大;因此需要总和计数有效的节点,排除孤立的节点;
- 记得反转不是反转一次
以下是改进后的(回头看了陈越姥姥的视频才发现new和old反了 Emmmm 思路一个样子吧QAQ)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 100002
typedef struct List
{
int next;
int data;
}*Pnode;
int reverse(struct List *list, int head, int k) ;
int main(int argc, char const *argv[])
{
int first_adress,count,k;
scanf("%d%d%d",&first_adress,&count,&k);
Pnode Node=(Pnode)malloc(sizeof(struct List)*MAXSIZE);
memset(Node,0,sizeof(struct List)*MAXSIZE);
int i,j;
for(i=0;i<count;i++)
{
int temp;
scanf("%d",&temp);
scanf("%d%d",&Node[temp].data,&Node[temp].next);
}
Node[MAXSIZE-1].next=first_adress;//head
int sum=0;//有效节点
for(i=Node[MAXSIZE-1].next;i!=-1;i=Node[i].next)
{
sum++;
}
for(j=sum/k,i=MAXSIZE-1;j>0&&i!=-1;j--)
{
i=reverse(Node,i,k);
}
for(i=Node[MAXSIZE-1].next;i!=-1;i=Node[i].next)
{
if(Node[i].next!=-1)
printf("%05d %d %05d\n",i,Node[i].data,Node[i].next);
else
printf("%05d %d -1\n",i,Node[i].data,Node[i].next);
}
system("pause");
return 0;
}
int reverse(struct List *list, int head, int k)
{
int i, j, p;
int nexthead;
for(j = 0, p = list[head].next; j < k && p != -1; ++j)
p = list[p].next;
nexthead = list[head].next;
list[head].next = p;
for(j = 0, i = nexthead; j < k && i != -1; ++j)
{
p = list[i].next;
list[i].next = list[head].next;
list[head].next = i;
i = p;
}
return nexthead;
}
全部过掉惹