02-线性结构3 Reversing Linked List (25 分)
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 (≤10
5
) 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 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
Sample Output:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
这道题需要注意的地方是,如果在中间翻转链表后,上段链表的尾要接上翻转后的头,下端的头要接上翻转后的尾
#include<iostream>
#include<string>
#include<queue>
#define MAX 100005
using namespace std;
int head;
typedef struct LIST
{
int next,pri;
int data;
bool ans;
}LIST;
LIST a[MAX];
//单向链表翻转法
void Re(int first,int last,int R){
int p, q, r;
p = first;
q = a[p].next;
r = (R-2>0)?(a[q].next):q; //r的位置
if(first ==head)
head = last;
for (int i=1 ;i<R ;i++)
{
a[q].next = p;
p = q;
q = r;
if(i< R)
r = (R-2)>0?(a[q].next):q;
else
;
}
}
//这两个是打印答案的函数
void P2(int i){
if(i==-1)
{
cout << i << endl;
return;
}
int s = i;
int t = 0;
while (s>0)
{
t++;
s = s / 10;
}
t = 5 - t;
while(t>0)
{
cout << "0";
t--;
}
if(i)
cout << i;
}
void PRINT(){
for (int i = head; i != -1; i = a[i].next)
{
P2(i);
cout << " " << a[i].data << " ";
P2(a[i].next);
if (a[i].next!=-1)
cout << endl;
a[i].ans = 0;
}
}
int main(){
int L=1,L2,R; //头地址,表长,以及翻转长度
int t1, t2;
int ta=-1, tb=-1;
cin >>head >> L2 >> R;
//创造长度链表
for (int i = 1; i <= L2; i++)
{
int j;
scanf("%d%d%d", &j, &t1, &t2);
a[j].data = t1;
a[j].next = t2;
a[j].ans = 1;
}
int p1, q1;
p1=q1 = head;
//将前驱连接上
while (a[p1].next!=-1)
{
q1 = a[p1].next;
a[q1].pri = p1;
p1 = q1;
L++;
}
p1=q1 = head;
//此处开始连接链表
if(R==1)
;
else
for (int i = 1; i <= L; i++,q1 = a[q1].next)
if(i%R==0)
{
if(i==R)
head = q1;
//记录翻转前尾结点的下个位置
tb = a[q1].next;
for (int p = p1,q=tb,r =a[p1].next; p != tb; )
{
a[p].next = q;
q = p;
p = r;
r = a[r].next;
}
//上一个翻转段的尾结点指向现翻转段的头结点
//如果是第一次就不记录上个尾结点,如果是就记录
if(ta==-1)
ta = p1;
else
{
a[ta].next = q1;
ta = p1;
}
p1 = q1 =tb;
i++;
}
/*
for (int pp = head; pp != -1;pp=a[pp].next)
printf("%05d %d %05d\n", pp,a[pp].data,a[pp].next);
*/
PRINT();
// P3();
system("PAUSE");
return 0;
}