题目
A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive N (< 105) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the address of the node in memory, Key is an integer in [-105, 105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.
Output Specification:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.
Sample Input:
5 00001 11111 100 -1 00001 0 22222 33333 100000 11111 12345 -1 33333 22222 1000 12345
Sample Output:
5 12345 12345 -1 00001 00001 0 11111 11111 100 22222 22222 1000 33333 33333 100000 -1
注意点:
1、输入的数据可能是多个链表(也可以包含其他和链表不相关的数据)
2、输入的数据可能不是链表
3、输入的头结点指向的位置可能为空,即为空链表
代码:
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct node //链表中的点 { int adress; int val; int next; }; bool cm(const node &n1,const node &n2); //用于排序 int main() { int n,head; //数量,链表头 node *in_put; //用于输入数据 in_put=new node[100001]; vector<node> data; //用于保存真实链表中的数据 node temp_n; cin>>n>>head; if(n==0||head==-1) //!!!输入链表本身为空 { cout<<"0 -1"; return 0; } int i; for(i=0;i<100001;i++) //特殊标记,防止头结点指向的单元不存在 in_put[i].next=-2; for(i=0;i<n;i++) //输入数据 { scanf("%d %d %d",&temp_n.adress,&temp_n.val,&temp_n.next); in_put[temp_n.adress]=temp_n; } if(in_put[head].next==-2) //!!!头结点指向的地址为空 { cout<<"0 -1"; return 0; } while(head>0) //依次扫描链表中的数据,并暂存到data中 { data.push_back(in_put[head]); head=in_put[head].next; } sort(data.begin(),data.end(),cm); //排序 cout<<data.size(); //输出 printf(" %05d\n",data[0].adress); for(i=0;i<data.size()-1;i++) { printf("%05d %d %05d\n",data[i].adress,data[i].val,data[i+1].adress); } printf("%05d %d -1",data[i].adress,data[i].val); delete [] in_put; return 0; } bool cm(const node &n1,const node &n2) { return n1.val<n2.val; }