1074. Reversing Linked List (25)

来源:互联网 发布:哪里有学淘宝拍摄的 编辑:程序博客网 时间:2024/06/07 15:21


时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if K = 4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (<= 105) which is the total number of nodes, and a positive K (<=N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:
00100 6 400000 4 9999900100 1 1230968237 6 -133218 3 0000099999 5 6823712309 2 33218
Sample Output:
00000 4 3321833218 3 1230912309 2 0010000100 1 9999999999 5 6823768237 6 -1

这题写了好久,按照姥姥的说法,就真的用链表。。。

刷乙级的时候写的 反转链表 


真佩服以前的我。。 。  现在肯定写不出来了


代码好好画图理解吧


#include<stdio.h>#include<stdlib.h>struct Node{int add1;int data;int add2;struct Node *next;};typedef struct Node *node;int main(){int addstart,n,k,i,cou=1,flag=0,count=0;scanf("%d %d %d",&addstart,&n,&k);struct Node stu[100000];node first,p;int add1,data,add2;for(i=0;i<n;i++){scanf("%d %d %d",&add1,&data,&add2);stu[add1].add1=add1;stu[add1].data=data;//stu[add1].add2=add2;if(add2!=-1) stu[add1].next=&stu[add2];else stu[add1].next=NULL;if(addstart==add1){first=&stu[add1];p=&stu[add1];}}//已经排好序p=(node)malloc(sizeof(struct Node));p->next=first;first=p;//开始反转if(k==1){p=first->next;while(p){if(p->next)printf("%05d %d %05d\n",p->add1,p->data,p->next->add1);else printf("%05d %d %d\n",p->add1,p->data,-1);p=p->next;}return 0;}//以上k=1; p=first->next;while(p){count++; p=p->next;}//有几个有用节点 !!   存在废节点 遍历所有有用的节点  node p1,p2,p3=NULL,tempfirst[count];p1=first->next;p2=p1->next;if(p2!=NULL)p3=p2->next;int flagfirst=1; int dijibo=0;while(count>=k){//  不是n!!!!!!  cou=1;int flag1=1;while(cou<k){p2->next=p1;if(flag1){tempfirst[dijibo]=p1;p1->next=NULL;flag1=0;}p1=p2;p2=p3;if(p2!=NULL)p3=p2->next;if(cou==k-1&&dijibo){tempfirst[dijibo-1]->next=p1;}cou++;}if(flagfirst){first->next=p1;flagfirst=0;}count=count-k;if(count>=k){p1=p2;p2=p3;if(p2!=NULL)p3=p2->next;//p3=p2->next;dijibo++;}}if(p2){//末尾还有结点 tempfirst[dijibo]->next=p2;}p=first->next;while(p){if(p->next)printf("%05d %d %05d\n",p->add1,p->data,p->next->add1);else printf("%05d %d %d\n",p->add1,p->data,-1);p=p->next;}}