1052 Linked List Sorting (25 分)

2021/7/13 23:38:46

本文主要是介绍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 (<) 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 −.

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 [−], 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
 题解:使用静态链表,将地址保存在节点中,遍历链表进行标记(排除掉非链表节点),排序输出  
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000010;
#define inf 0x3fffffff
struct Node{
    int address,data,next;
    bool flag;
}node[maxn];
bool cmp(Node a,Node b){
    if(a.flag==false||b.flag==false){
        return a.flag>b.flag;
    }
    else if(a.data!=b.data){
        return a.data<b.data;
    }
}
int main(){
    int n,address,begin;
    scanf("%d %d",&n,&begin);
    int data,next,count=0;
    for(int i=0;i<n;i++){
        scanf("%d %d %d",&address,&data,&next);
        node[address].address=address;
        node[address].data=data;
        node[address].next=next;
    }
    int p=begin;
    while(p!=-1){
        count++;
        node[p].flag=true;
        p=node[p].next;
        
    }
    sort(node,node+maxn,cmp);
    if(count==0){
        printf("0 -1\n");
        return 0;
    }
    printf("%d %05d\n",count,node[0].address);
    int i;
    for(i=0;i<count-1;i++){
        node[i].next=node[i+1].address;
        printf("%05d %d %05d\n",node[i].address,node[i].data,node[i].next);
    }
    printf("%05d %d %d\n",node[i].address,node[i].data,-1);
    return 0;
}

 



这篇关于1052 Linked List Sorting (25 分)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程