您的位置:首页 > 其它

PAT (Basic Level)1025. 反转链表

2016-03-01 22:57 459 查看
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 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

输出样例:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 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 100000

struct 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 3
1 2 2
2 4 3
3 5 4
4 3 5
5 5 6
6 6 7
7 7 8
8 8 -1

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: