PAT (Basic Level)1025. 反转链表

来源:互联网 发布:太空软件安卓 编辑:程序博客网 时间:2024/06/05 11:12

http://www.patest.cn/contests/pat-b-practise/1025

题目描述:

给定一个常数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
唉呀妈呀,这题整了一晚上。由于地址是五位整数格式,所以,我们可以开一个很大的数组,以空间换时间。地址的值就是该节点在数组中的索引。然后我是增加了一个previous node属性,便于count计数到K,也就是要反转的链末时,可以回溯。这样,只需要O(n)的时间。但是要注意输出中的next值是要改成反转后链的下一个节点的地址,尤其是注意每一段的最后一个地址。


#include <iostream>#include <string>#include <algorithm> #include <cmath>#include <iomanip>#include <ctype.h>using namespace std;#define max 100000struct node {int addr ;int data ;int next ;int pre ;};node nodes[max] ;string intout (int n){if (n==-1) return "-1";string s = "";for (int i = 10000 ; i>=10 ; i/=10){char ch = n/i+'0' ;n %= i ;s += ch ;}char ch = n+'0' ;s += ch ;return s;}int main(){int head = 0 ;int K = 0, N = 0;cin >> head >> N >> K ;while (N--){int ad = 0 ;cin >> ad ;nodes[ad].addr = ad ;cin >> nodes[ad].data >> nodes[ad].next ;}int current = head ;int nextAd = -1;int count = 1 ;int tail = head ;bool flag = 0;while ( current != -1){if (count == K)//need to return{tail = nodes[current].next ;int temp = current ;if (flag==1) printf ("%s\n", intout(current).c_str()) ;while (count){if (count==1 ){flag = 1;printf ("%s %d ", intout(nodes[temp].addr).c_str(), nodes[temp].data) ; } else printf ("%s %d %s\n", intout(nodes[temp].addr).c_str(), nodes[temp].data, intout(nodes[temp].pre).c_str()) ;temp =  nodes[temp].pre ;count--;}}nextAd = nodes[current].next ;if (nextAd != -1) nodes[nextAd].pre = current ;current = nextAd ;count ++ ;}printf("%s\n" , intout(tail).c_str());while (tail != -1){printf ("%s %d %s\n", intout(nodes[tail].addr).c_str(), nodes[tail].data, intout(nodes[tail].next).c_str()) ;tail = nodes[tail].next ;} if (head == -1) printf("-1");return 0;}/*1 8 31 2 22 4 33 5 44 3 55 5 66 6 77 7 88 8 -1*/


0 0
原创粉丝点击