pat 1074(有一坑点尚未找到)

局部翻转链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <cstdio>
#include <cstring>
#include <sstream>
#define MAX 100010
using namespace std;
typedef struct
{
int data;
int next;
}Lnode;
int main()
{
int begin , N , k;
//cin>>begin>>N>>k;
scanf("%d%d%d" , &begin , &N , &k);
Lnode List[MAX];
if(k > N)
k = N;
int i , j;
for(i = 0 ; i < N ; ++i)
{
int ad , data , next;
//cin>>ad>>data>>next;
scanf("%d%d%d" , &ad , &data , &next);
List[ad].data =data;
List[ad].next = next;
}
int group;
if(k != 0)
{
group = N / k;
}
else
group = 1;
int pre[MAX];//前驱
int first , last , head = begin;
//断链怎么接?
if(k >1)
{
int mod_first[MAX];
int mod_last[MAX];//此俩数组用来解决记录断链位置
for(i = 0 ; i < group ; ++i)
{
j = 0 ;
int temp = begin;
while(true)
{
pre[j] = temp;
temp = List[temp].next;
++j;
if(j >= k-1)
break;
}
first = temp;
if(i == 0)
head = first;
int tail = List[first].next;//保存断点
for(j = k-2 ; j >= 0 ; --j)
{
List[temp].next = pre[j];
temp = pre[j];
}
last = temp;
mod_first[i] = last;
mod_last[i] = first;
List[last].next = tail;
begin = tail;
}
for(i = 0 ; i < group-1; ++i)//此循环用来链接断链
{
List[mod_first[i]].next = mod_last[i+1];
}
}
//display
//cout<<endl;
int temp = head;
for(i = 0 ; i < N ; ++i)
{
string s;
stringstream ss;
ss<<temp;
ss>> s;
//string s = (string)temp;
if(s.size() < 5)
{
int k = 5 - s.size();
for(int x = 0 ; x <k ; ++x)
{
printf("0");
}
}
//cout<<temp<<" "<<List[temp].data<<" ";
printf("%d %d " , temp , List[temp].data);
//format
string s2;
stringstream ss2;
ss2<<List[temp].next ;
ss2>>s2;
// cout<<s2<<endl;
if(s2.size() < 5 && List[temp].next >=0)
{
int k = 5 - s2.size();
for(int x = 0 ; x <k ; ++x)
{
printf("0");
}
}
//cout<<List[temp].next<<endl;
printf("%d\n" , List[temp].next);
if(List[temp].next == -1) //用来处理无效节点的
break;
/*
00000 6 3
00000 1 11111
11111 2 22222
22222 3 -1
33333 4 44444
44444 5 55555
55555 6 -1
*/
temp = List[temp].next;
}
return 0;
}

热评文章