Pat(Advanced Level)Practice--1052(Linked List Sorting)

来源:互联网 发布:天涯八卦是什么软件 编辑:程序博客网 时间:2024/04/28 04:44

Pat1052代码

题目描述:

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 0000111111 100 -100001 0 2222233333 100000 1111112345 -1 3333322222 1000 12345
Sample Output:
5 1234512345 -1 0000100001 0 1111111111 100 2222222222 1000 3333333333 100000 -1

需要注意的地方:
1,可能某些节点,不在链表上。
2,head node 节点的值可能为-1,这样会出段错误,直接输出 0 -1即可
AC代码:
#include<cstdio>#include<vector>#include<algorithm>#define MAX 100001using namespace std;typedef struct Node{int addr;int key;int next;}Node;bool cmp(const Node &l,const Node &r){if(l.key<r.key)return true;elsereturn false;}int main(int argc,char *argv[]){int n,first;int count;int i,j;int index;Node N[MAX];vector<Node> v;scanf("%d%d",&n,&first);for(i=0;i<n;i++){scanf("%d",&index);scanf("%d%d",&N[index].key,&N[index].next);N[index].addr=index;}index=first;count=0;while(index!=-1){count++;v.push_back(N[index]);index=N[index].next;}sort(v.begin(),v.end(),cmp);if(v.size()==0)printf("0 -1\n");else{printf("%d %05d\n",count,v[0].addr);for(i=0;i<count-1;i++){v[i].next=v[i+1].addr;printf("%05d %d %05d\n",v[i].addr,v[i].key,v[i].next);}printf("%05d %d %d\n",v[count-1].addr,v[count-1].key,-1);}return 0;}


0 0
原创粉丝点击