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 33218Sample Output:
00000 4 33218 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
#include<stdio.h> #include<iostream> #include<vector> using namespace std; const int MAX = 100002; struct Node{ int add; int data; int next; Node(){ next = -1; } }buf[MAX]; vector<Node>V_input; vector<Node>V_ans; int main(void){ freopen("F://Temp/input.txt", "r",stdin); int start_add, all_nodes, N; scanf("%d%d%d", &start_add, &all_nodes, &N); for (int i = 0; i < all_nodes; i++){ int cur_add, next_add, data; scanf("%d%d%d", &cur_add, &data,&next_add); buf[cur_add].add = cur_add; buf[cur_add].next = next_add; buf[cur_add].data = data; } int i; for (i = start_add; buf[i].next != -1; i = buf[i].next){ V_input.push_back(buf[i]); } V_input.push_back(buf[i]); int idx = 0; while (idx + N <= V_input.size()){ //这里要用V_input.size()而不是用all_nodes,因为会有无用节点的存在 for (int i = idx + N - 1; i >= idx; i--){ Node *tmp = &V_input[i]; if (i != idx){ tmp->next = V_input[i - 1].add; }//从后向前来,next地址变成前一个节点的地址 else if(idx + N != V_input.size()){ tmp->next = V_input[idx + N].add; }//第一个节点的地址变成向后第N个节点的地址 else { tmp->next = -1; }//当碰到10个节点要55倒序的时候,要指定为-1,而不能找到向后第N个节点的地址 V_ans.push_back(*tmp); } idx += N; } for (int i = idx; i < V_input.size(); i++){ V_ans.push_back(V_input[i]); } for (int i = 0; i < V_input.size(); i++){ if (i == V_input.size() - 1){ printf("%05d %d -1\n", V_ans[i].add, V_ans[i].data); } else{ printf("%05d %d %05d\n", V_ans[i].add, V_ans[i].data, V_ans[i+1].add); } } return 0; }