忙活了将近整整一天,终于把这个题给搞定了,因为没有用到链表的功能,也没有因为提示说不能先排序,排序必挂而放弃尝试,最终走了无数的弯路,还是给解决了。。
#include <stdio.h>
typedef struct{
int curAdd;
int seqNum;
int nextAdd;
}Node;
int main()
{
int startAdd;
int N, K;
scanf("%d %d %d", &startAdd, &N, &K);
Node a[100000];
int curAddI, seqNumI, nextAddI;
for(int i=0; i<N; i++)
{
scanf("%d %d %d", &curAddI, &seqNumI, &nextAddI);
a[i].curAdd = curAddI;
a[i].seqNum = seqNumI;
a[i].nextAdd = nextAddI;
}
int j = 0; //j is the order of the array from 0 to N-1.
Node temp;
int curNum = 0;
int effectNode = 0;
int s;
while(startAdd != -1)
{
if(startAdd != a[j].curAdd)
{
j++;
}
else
{
effectNode++;
//printf("effectNode = %d\n", effectNode);
startAdd = a[j].nextAdd;
temp = a[j];
for(s=j-1;s>=curNum;s--)
{
a[s+1] = a[s];
}
a[curNum] = temp;
curNum++;
j = curNum;
}
}
/*for(int nn=0; nn<effectNode; nn++)
{
if(a[nn].nextAdd == -1)
printf("%05d %d %d\n",a[nn].curAdd, a[nn].seqNum, -1);
else
printf("%05d %d %05d\n",a[nn].curAdd, a[nn].seqNum, a[nn].nextAdd);
}*/
int value = K;
int count = 0;
int m = K-1; //m+1 is the output number in one round.
int total = effectNode;
if(effectNode < K)
{
for(int mm = 0; mm<effectNode-1; mm++)
{
printf("%05d %d %05d\n", a[mm].curAdd, a[mm].seqNum, a[mm+1].curAdd);
}
printf("%05d %d %d\n",a[effectNode-1].curAdd, a[effectNode-1].seqNum, -1);
return 0;
}
else if(effectNode == K)
{
for(; m>0; m--)
{
printf("%05d %d %05d\n", a[m].curAdd, a[m].seqNum, a[m-1].curAdd);
}
printf("%05d %d %d\n", a[0].curAdd, a[0].seqNum, -1);
return 0;
}
else
{
while(effectNode>=value)
{
if(total%K == 0)
{
for(; m>=0; m--)
{
if((m != 0))
{
printf("%05d %d %05d\n", a[m+count].curAdd, a[m+count].seqNum, a[m+count-1].curAdd);
}
else if((m == 0) && (count == (total-value)))
{
printf("%05d %d %d\n",a[m+count].curAdd, a[m+count].seqNum, -1);
return 0;
}
else
{
printf("%05d %d %05d\n", a[m+count].curAdd, a[m+count].seqNum, a[count+2*value-1].curAdd);
}
}
m = K-1;
effectNode -=value;
count +=value;
}
else
{
for(; m>=0; m--)
{
if(m != 0)
{
printf("%05d %d %05d\n", a[m+count].curAdd, a[m+count].seqNum, a[m+count-1].curAdd);
}
else if((m == 0) && ((total-count)>2*value))
{
printf("%05d %d %05d\n", a[m+count].curAdd, a[m+count].seqNum, a[count+2*value-1].curAdd);
}
else
{
printf("%05d %d %05d\n", a[m+count].curAdd, a[m+count].seqNum, a[count+value].curAdd);
}
}
m = K-1;
effectNode -=value;
count +=value;
}
}
for(;count<total-1;count++)
{
printf("%05d %d %05d\n",a[count].curAdd, a[count].seqNum, a[count+1].curAdd);
}
printf("%05d %d %d\n",a[total-1].curAdd, a[total-1].seqNum, -1);
}
return 0;
}