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 33218Sample Output:00000 4 3321833218 3 1230912309 2 0010000100 1 9999999999 5 6823768237 6 -1#include<stdio.h>#include<algorithm>#include<stack>using namespace std;struct Node{ int data; int next;}node[100000];//定義靜態鏈表節點struct record{ int address; //int next;};//用于反轉鏈表int main(){ for (int i = 0; i < 100000; i++) { node[i].data = 0; node[i].next = -1; }//初始化 int head, N, K; scanf("%d%d%d", &head, &N, &K); int address, data, next; while (N--) { scanf("%d%d%d", &address, &data, &next); node[address].data = data; node[address].next = next;//鏈接各節點 } int count = 0;//計數器 int addressNow = head; int pre; stack<record> sta;//用于暫存要被逆轉連接的節點 record temprecord;//保存節點地址,本來以為要保存下一個節點的地址,其實根本不需要,也不想改了就這樣吧 int oldLast;//上一次逆轉后指向最后一個節點的指針 while (addressNow!= -1) { temprecord.address = addressNow; //temprecord.next = node[addressNow].next; sta.push(temprecord); pre = addressNow; addressNow = node[addressNow].next; count++; if (count%K == 0) { if (count == K) head = pre;//第一個開始反轉的節點成為頭了 if (!sta.empty()) { sta.pop(); } if (pre != head) { node[oldLast].next = pre; }//如果不是第一個那么需要將上一次反轉后的最后一個節點的下個地址做修改 //將樣例中的K由4改為2你就知道為什么了 for (int i = 0; i < K-1; i++) { node[pre].next = sta.top().address;//逆轉鏈表 pre = sta.top().address; if (!sta.empty()) { sta.pop(); } } node[pre].next = addressNow;//修改反轉節點的最后一個節點的下一個地址, //若后面不會再反轉,那么就是當前掃描的節點的地址,注意我是先計數后又把指針 //往后移一位了 oldLast = pre;//保存反轉節點的最后一個節點的地址 } } addressNow = head; while (addressNow!= -1) { if(node[addressNow].next!=-1) printf("%05d %d %05d/n", addressNow, node[addressNow].data, node[addressNow].next); else printf("%05d %d %d/n", addressNow, node[addressNow].data, node[addressNow].next); addressNow = node[addressNow].next; } return 0;}/*注意把每次反轉后的節點的下一個地址修改正確,比如說1 2 3 4 5 6,反轉個數K為2時,應該是2 1 4 3 6 5,這時要記得把1跟4連上,3跟6連上。*/
新聞熱點
疑難解答