测试用例很坑。注意链表为空的情形,并且可能有孤节点。
#include <iostream>
#include <list>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct Node
{
int addr;
int value;
int next;
int tag;
};
bool compare(const Node &s1, const Node &s2)
{
return s1.value < s2.value;
}
Node linklist[100000];
int main()
{
int startposition,n;
int position, value, next;
list<Node> mylist;
list<Node>::const_iterator itr;
cin >> n >> startposition;
for(int i = 0; i < n; i++)
{
cin >> position >> value >> next;
linklist[position].addr = position;
linklist[position].value = value;
linklist[position].next = next;
linklist[position].tag = 1;
}
for(int i = startposition; i != -1;)
{
Node node = linklist[i];
if(node.tag == 0)
break;
mylist.push_back(node);
i = node.next;
}
mylist.sort(compare);
if(!mylist.empty())
{
for(itr = mylist.begin(); itr != mylist.end(); ++itr)
{
Node node = (Node)*itr;
if(itr == mylist.begin())
{
printf("%d %05d\n", mylist.size(), node.addr);
printf("%05d %d ", node.addr, node.value);
}
else
printf("%05d\n%05d %d ", node.addr, node.addr, node.value);
}
printf("-1\n");
}
else
{
if(startposition == -1)
printf("0 -1\n");
else
printf("0 %05d\n", startposition);
}
return 0;
}