1025. 反转链表 (25)

来源:互联网 发布:sai绘画软件mac 编辑:程序博客网 时间:2024/06/11 19:25

给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转。例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;如果K为4,则输出应该为4→3→2→1→5→6,即最后不到K个元素不反转。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址、结点总个数正整数N(<= 105)、以及正整数K(<=N),即要求反转的子链结点的个数。结点的地址是5位非负整数,NULL地址用-1表示。

接下来有N行,每行格式为:

Address Data Next

其中Address是结点地址,Data是该结点保存的整数数据,Next是下一结点的地址。

输出格式:

对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。

输入样例:
00100 6 400000 4 9999900100 1 1230968237 6 -133218 3 0000099999 5 6823712309 2 33218
输出样例:
00000 4 3321833218 3 1230912309 2 0010000100 1 9999999999 5 6823768237 6 -1

#include "iostream"#include <string>#include <vector>#include <math.h>using namespace std;struct node{int addr;int data;int next;};int main(){int N = 0, K = 0;int addr = 0;vector<node> input(100000);vector<node> order;vector<node> output;node tmp;cin >> addr >> N >> K;for (int i = 0; i < N; i++){cin >> tmp.addr >> tmp.data >> tmp.next;input[tmp.addr] = tmp;}while (addr != -1)                     // 对输入进行排序{order.push_back(input[addr]);addr = input[addr].next;}N = order.size();                       // 注意废点的存在int count = K - 1;// 调整反转后的顺序while (count<N){for (int i = count; i >  count - K; i--){output.push_back(order[i]);}count += K;}for (int i = count - K + 1; i < N; i++){output.push_back(order[i]);}// 纠正反转后的地址for (int i = N-1; i > 0; i--){output[i-1].next = output[i].addr;}for (int i = 0; i< N-1; i++){printf("%05d %d %05d\n", output[i].addr, output[i].data, output[i].next);}printf("%05d %d -1\n", output[N - 1].addr, output[N - 1].data);  // 注意最后一个-1的问题system("pause"); return 0;}


0 0
原创粉丝点击