链表的逆转,定义一个结构体来模拟
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
struct node
{
int next;
int data;
}a[100005];
int prehead; //指向这一次逆转的最后一个节点
int nexthead; //指向下一次逆转的第一个节点
int Reverse(int head,int k)
{
int cnt = 1;
int newn = head;
int old = a[newn].next;
while(cnt < k)
{
int tmp = a[old].next;
a[old].next = newn;
newn=old;
old = tmp;
cnt++;
}
a[head].next = old;
prehead=head;
nexthead=old;
return newn;
}
int main()
{
int head,n,k;
cin>>head>>n>>k;
int add,data,next;
if(head==-1)
{
printf("-1\n");
return 0;
}
for(int i=0;i<n;i++)
{
cin>>add>>data>>next;
a[add].next=next;
a[add].data=data;
}
int p=head;
int sum=0;
while(p!=-1)
{
sum++;
p = a[p].next;
}
head = Reverse(head,k);
for(int i=1;i<sum/k;i++)
{
int preshead=prehead;
a[preshead].next=Reverse(nexthead,k);
}
while( a[head].next != -1 )
{
printf("%05d %d ",head,a[head].data);
printf("%05d\n" ,a[head].next);
head = a[head].next;
}
printf("%05d %d -1",head,a[head].data);
}