PAT_A 1052. Linked List Sorting (25)

来源:互联网 发布:unity3d初音炫舞源码 编辑:程序博客网 时间:2024/06/05 06:09

1052. Linked List Sorting (25)

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 andthe 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 Nextwhere 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 totalnumber 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 12345Sample Output:5 1234512345 -1 0000100001 0 1111111111 100 2222222222 1000 3333333333 100000 -1
  • 分析:

    • 题目:给你几个节点以及头结点的地址,对链表排序。注意这些节点可能不是个链表上的,所以需要头结点地址;如果没有节点,头结点地址-1,这是特殊情况。想起春天pat那个case没过就是没注意特殊情况(上次是个图,忘了检查是否连通)
    • 解题:首先我们用数组排序即可,从输出看,我们仅仅需要修改排序后的next节点而节点地址和值均不变。要多一步预处理,判断哪些节点在所给head地址的链表上
  • code:

#include<iostream>#include<vector>#include<algorithm>#include<cstdio>using namespace std;struct Node{    int ads;    int key;    int next;};int NEXT[100010];int one[100010];vector<Node> nodes;bool comp(Node a,Node b){    return a.key<b.key;}int main(){    freopen("in","r",stdin);    int N,ads,tmp;    Node node;    fill_n(NEXT,100010,-1);    scanf("%d%d",&N,&ads);    for(int i=0;i<N;i++)    {        scanf("%d%d%d",&node.ads,                    &node.key,                    &node.next);        nodes.push_back(node);        NEXT[node.ads]=node.next;    }     //attention1:这些节点中有些可能不在一条链上    int count=0;//记录链中的节点    while(ads>0&&NEXT[ads]>0)    {        count++;        tmp=ads;        ads=NEXT[ads];        NEXT[tmp]=-2;    }    if(ads>=0)//attention2 head ads=-1则表示没有节点     {        NEXT[ads]=-2;        count++;    }    sort(nodes.begin(),nodes.end(),comp);    printf("%d ",count);    for(int i=0;i<N;i++)    {        if(NEXT[nodes[i].ads]==-2)        printf("%.5d\n%.5d %d ",nodes[i].ads,                    nodes[i].ads,                    nodes[i].key);    }    printf("-1\n");    return 0;}
  • AC
    pat_a1052
原创粉丝点击