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 (≤105) 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
大意:n个结点构成一条单向链L(单向链长度不一定为n,可能有多余结点),给定整数k,在L上每k个长度进行翻转。按结点地址,结点数据,指向结点地址的格式输出翻转后的链。
作死用动态链写,写后发现各种指针混乱的令人头疼,但自己作的死哭着也要改好。
简单点的代码就是数组存储加algorithm里的reverse函数,网上很多。
下面是我巨麻烦的代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef struct Node *Stack;
struct Node
{
int add;
int dat;
Stack Next;
};
pair<int,int> Data[100005];
pair<Stack,Stack> p;
int main()
{
Stack push(Stack top,int k);
pair<Stack,Stack> pop(Stack top,int k);
int top,n,k;
//输入
cin>>top>>n>>k;
for(int i=0;i<n;i++)
{
int b;
cin>>b;
cin>>Data[b].first>>Data[b].second;
}
int i=0,m,j,t;
t=top;
//计算单向链真实长度
while(t!=-1)
{
i++;
t=Data[t].second;
}
// m需要翻转的段数 j不需要翻转的结点数
m=i/k;
j=i%k;
//s 进行不断翻转的栈
Stack s=(Stack)malloc(sizeof(Node));
s->add=top;
s->dat=Data[top].first;
s->Next=NULL;
//结果链 h为头 f为尾
Stack f,h=(Stack)malloc(sizeof(Node));
f=h;
f->Next=NULL;
//m次翻转 将每次翻转后的段放入结果链后
while(m--)
{
s=push(s,k);
p=pop(s,k);
f->Next=p.first;
f=p.second;
f->Next=NULL;
}
//将不用翻转的结点依次放入结果链后
if(j)
{
t=s->add;
while(t!=-1)
{
Stack x=(Stack)malloc(sizeof(Node));
x->add=t;
x->dat=Data[t].first;
f->Next=x;
f=x;
f->Next=NULL;
t=Data[t].second;
}
}
//打印
h=h->Next;
while(h)
{
if(h->Next)
{
printf("%05d %d %05d\n",h->add,h->dat,h->Next->add);
h=h->Next;
}
else
{
printf("%05d %d -1\n",h->add,h->dat);
h=h->Next;
}
}
return 0;
}
Stack push(Stack top,int k)
{
for(int i=0;i<k;i++)
{
Stack s=(Stack)malloc(sizeof(Node));
s->add=Data[top->add].second;
if(s->add==-1) s->dat=-1;
else s->dat=Data[s->add].first;
s->Next=top;
top=s;
}
return top;
}
pair<Stack,Stack> pop(Stack top,int k)
{
Stack l=top->Next,r=top;
for(int i=0;i<k;i++)
{
r=r->Next;
}
top->Next=NULL;
pair<Stack,Stack> p(l,r);
return p;
}