题目来源:PTA02-线性结构2 Reversing Linked List (25分)
Question: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 4 00000 4 99999 00100 1 12309 68237 6 -1 33218 3 00000 99999 5 68237 12309 2 33218
Sample Output:
00000 4 33218 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
Show the code:
#include<iostream> #include<algorithm> //使用algorithm的reverse函数进行反转 using namespace std; const int MaxSize = 100000+10; struct LinkNode //节点,因为给定了地址值,用数组下标来表示地址,用next来指向下一地址(而不是指针) { int data; int next; }LinkNode[MaxSize]; int SeqList[MaxSize]; //简单的顺序表,用来存放节点间的(地址)连接关系 int main() { int FirstAddr,N,K; //N是输入的节点数,但这些节点不一定都能连在一起 cin>>FirstAddr>>N>>K;//输入第一行 int Address,Data,Next,i; for(i=0;i<N;i++) { cin>>Address>>Data>>Next; LinkNode[Address].data = Data; LinkNode[Address].next = Next; } int List_n=0; //把能连在一起的节点地址存入顺序表,List_n表示这些节点的数目 int p=FirstAddr; //p指示当前节点 while(p!=-1) { SeqList[List_n++] = p; p = LinkNode[p].next; } i=0; while(i+K<=List_n) { reverse(&SeqList[i],&SeqList[i+K]);//Reverses the order of the elements in the range [first,last) i=i+K; } for (i = 0;i < List_n-1;i++) //输出逆转后的“链表” { printf("%05d %d %05d ", SeqList[i], LinkNode[SeqList[i]].data, SeqList[i+1]);//%05d为输出5位整数,不足在前面补0 } printf("%05d %d -1 ", SeqList[i], LinkNode[SeqList[i]].data); //输出逆转后的“链表”的最后一项 return 0; }