【ZJU PAT】中国大学MOOC-DS(陈越)习题集-Reversing Linked List

来源:互联网 发布:云计算运用有哪些 编辑:程序博客网 时间:2024/06/07 20:48


02-1. Reversing Linked List (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 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, andNext 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
这题虽然说是要反转链表,不过实际上由于它是黑盒判定的,不在乎过程只看输出,所以也并非一定要改变每个结点的NEXT指针,只要能找到反转后下一个结点的地址并把它输出就好了。
在这里,内存地址是指定的,就不能贸然去用C里面的指针机制了,谁知道测试数据里的地址会指向哪一块致命内存。。。在姥姥英明的指点下就想到开辟一个足够大的结构数组作为模拟内存,以地址作为数组的下标,这样知道地址就可以直接访问对应的结点内容了。好在该题内存限制足够大,开个这样的数组还是绰绰有余的~当然这个数组只是作为虚拟内存使用,在程序中还需要一个数组来存放排序后的链表,方便随时找到链表中某个位置的结点。本来看别人的程序发现这个数组用malloc申请内存还懵了一下,后来才反应过来是自己一直用C99习惯了看到ANSI C的东西还觉得有点多此一举。。不过新标准发明了就是用的。。直接用变量申请个数组就好了*^_^*具体实现部分其实也没啥好讲的,无非就是在该反转的地方输出前一个结点的地址,由于链表已经存在数组中了,找某个结点前面、后面甚至隔几个的结点就都很容易了。
还有就是输出格式控制的问题了。。五位的地址很好解决直接%05d就行。。不过-1这个小婊砸在中间就要注意一下了,还是要好好考虑边界问题,在即将输出-1的时候要及时停下来,单独输出。。其他的等以后看的时候再说吧
代码就这样。反正PAT上是过了的,内存时间什么的都还好。。==
#include<stdio.h>#define MAX 100000struct vtlmmr{int DATA;int NEXT;};struct vtlmmr memory[MAX];int main(void){int head, num, k, i, j, addr;scanf("%d %d %d",&head,&num,&k);struct {int ADDR;int DATA;} list[num];for(i=0; i<num; ++i){scanf("%d",&addr);scanf("%d %d",&memory[addr].DATA, &memory[addr].NEXT);}i=0;int todo = head;while(todo != -1){list[i].ADDR = todo;list[i].DATA = memory[todo].DATA;todo = memory[todo].NEXT;i++; }int vldnum = i;int times = vldnum/k, rest = vldnum % k;for(i=0; i<times; i++){for(j = (i+1)*k-1; j>i*k; j--)printf("%05d %d %05d\n",list[j].ADDR, list[j].DATA, list[j-1].ADDR);if( i != times-1)printf("%05d %d %05d\n",list[j].ADDR, list[j].DATA, list[(i+2)*k-1].ADDR);if(rest==0 && i == times-1)printf("%05d %d -1\n",list[j].ADDR, list[j].DATA);if(rest != 0 && i== times-1)printf("%05d %d %05d\n",list[j].ADDR, list[j].DATA, list[times*k].ADDR);}if(rest != 0){for(j = times*k; j<vldnum-1; j++)printf("%05d %d %05d\n",list[j].ADDR, list[j].DATA, list[j+1].ADDR);printf("%05d %d -1\n",list[j].ADDR, list[j].DATA);}return 0;}

0 0
原创粉丝点击