标签:
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 12345Sample Output:
5 12345 12345 -1 00001 00001 0 11111 11111 100 22222 22222 1000 33333 33333 100000 -1
链表的插入和遍历。注意链表可以为空。
1 #include<cstdio> 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<queue> 6 #include<vector> 7 #include<cmath> 8 #include<string> 9 #include<map> 10 #include<set> 11 #include<stack> 12 using namespace std; 13 struct node{ 14 int k,next; 15 }; 16 #define h 100000 17 node line[100001]; 18 int main(){ 19 //freopen("D:\\INPUT.txt","r",stdin); 20 int first,n; 21 scanf("%d %d",&n,&first); 22 if(first==-1){//链表可能为空,这个太坑!! 23 printf("0 -1\n"); 24 return 0; 25 } 26 int i,add,k,next; 27 for(i=0;i<n;i++){ 28 scanf("%d %d %d",&add,&k,&next); 29 line[add].k=k; 30 line[add].next=next; 31 } 32 line[h].next=-1; 33 int p,pp,cur,count=1; 34 next=line[first].next; 35 line[first].next=line[h].next; 36 line[h].next=first; 37 while(next!=-1){//insert 38 cur=next; 39 pp=h;//头节点,指向p的前一个节点 40 p=line[h].next; 41 42 //cout<<"p: "<<p<<" "<<line[p].k<<endl; 43 //cout<<"cur: "<<cur<<" "<<line[cur].k<<endl; 44 45 while(p!=-1&&line[p].k<line[cur].k){ 46 pp=p; 47 p=line[p].next; 48 49 //cout<<pp<<" "<<p<<endl; 50 51 } 52 53 //cout<<"cur"<<endl; 54 55 next=line[cur].next; 56 line[cur].next=p; 57 line[pp].next=cur; 58 count++; 59 } 60 next=line[h].next; 61 printf("%d %05d\n",count,next); 62 while(next!=-1){//遍历 63 printf("%05d %d ",next,line[next].k); 64 if(line[next].next==-1){ 65 printf("%d",line[next].next); 66 } 67 else{ 68 printf("%05d",line[next].next); 69 } 70 printf("\n"); 71 next=line[next].next; 72 } 73 return 0; 74 }
pat1052. Linked List Sorting (25)
标签:
原文地址:http://www.cnblogs.com/Deribs4/p/4772275.html