1074. Reversing Linked List

来源:互联网 发布:sql注入的危害性 编辑:程序博客网 时间:2024/06/05 05:05

1074. Reversing Linked List (25)

时间限制
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<iostream>#include<vector>using namespace std;struct Node{int addr;int data;int next;Node(){next = -1;}}buf[100002];vector<Node> input;vector<Node> ans;int main(){freopen("F://Temp/input.txt", "r", stdin);int addr_start, node_nums, K;scanf("%d%d%d", &addr_start, &node_nums, &K);for(int i = 0; i < node_nums; i ++){int addr_cur, addr_next, data;scanf("%d%d%d", &addr_cur, &data, &addr_next);buf[addr_cur].addr = addr_cur;buf[addr_cur].data = data;buf[addr_cur].next = addr_next;}int i;for(i = addr_start; buf[i].next != -1; i = buf[i].next)input.push_back(buf[i]);input.push_back(buf[i]);int index = 0;while(index + K <= input.size()){for(i = index+K-1; i >= index; i --){Node *tmp = &input[i];if(i != index)tmp->next = input[i-1].addr;else if(index + K != input.size())tmp->next = input[index+K].addr;elsetmp->next = -1;ans.push_back(*tmp);}index += K;}for(i = index; i < input.size(); i ++)ans.push_back(input[i]);for(i = 0; i < input.size(); i ++){if(input.size()-1 == i)printf("%05d %d -1\n", ans[i].addr, ans[i].data);elseprintf("%05d %d %05d\n", ans[i].addr, ans[i].data, ans[i+1].addr);}return 0;}


0 0