Pat1074代码
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 33218Sample Output:
00000 4 33218 33218 3 12309 12309 2 00100 00100 1 99999 99999 5 68237 68237 6 -1
#include<cstdio>
#include<vector>
#define MAX 100005
using namespace std;
typedef struct Node
{
int addr;
int data;
int next;
}Node;
typedef struct Data
{
int data;
int next;
}Data;
int main(int argc,char *argv[])
{
int n,k,cur;
int index,i,j;
int first;
vector<Node> v(MAX);
Data D[MAX];
scanf("%d %d %d",&first,&n,&k);
for(i=0;i<n;i++)
{
int addr,data,next;
scanf("%d %d %d",&addr,&data,&next);
D[addr].data=data;
D[addr].next=next;
}
int size=0;
cur=first;
while(1)//将链表串起来
{
Node temp;
temp.addr=cur;
temp.data=D[cur].data;
temp.next=D[cur].next;
v[size]=temp;
size++;
if(D[cur].next==-1)
break;
cur=D[cur].next;
}
int loop=size/k;
for(i=1;i<=loop;i++)//反转
{
j=i*k-1;
for(int m=1;m<=k;m++)
{
if(i<loop&&m==k)//反转中间的K个元素,例如 1 2 3 4 5 6 7 ,k=3
v[j].next=v[(i+1)*k-1].addr;//一次循环后1指向6
else if(i==loop&&m==k)
{
if(size%k==0)//如果反转的是最后一个元素,next置-1
v[j].next=-1;
else//如果不能全部反转,next指向不用反转的地址
v[j].next=v[loop*k].addr;
}
else
v[j].next=v[j-1].addr;//反转,将next指向前面的地址
if(v[j].next==-1)
printf("%05d %d %d\n",v[j].addr,v[j].data,v[j].next);
else
printf("%05d %d %05d\n",v[j].addr,v[j].data,v[j].next);
j--;
}
}
for(i=loop*k;i<size;i++)
if(v[i].next==-1)
printf("%05d %d %d\n",v[i].addr,v[i].data,v[i].next);
else
printf("%05d %d %05d\n",v[i].addr,v[i].data,v[i].next);
return 0;
}