PAT 1052. Linked List Sorting

本文介绍了一种基于输入链表的节点排序算法,该算法通过遍历链表将节点存储,并根据节点的数值进行排序,最后输出排序后的链表。文章包含完整的C++实现代码。

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

分析

这题首先从给的head address开始遍历,直到为-1,把遍历中的节点储存起来,这是因为并不是所有给的节点都在list中,在list中的是head address到-1之间的所有节点。然后按节点的data排序。输出时,第一行输出节点个数,注意是list中节点的个数和头结点的id,然后从第二行开始除了最后一行每行输出该节点的id,该节点的data,下一个节点的id。最一行输出节点的id,节点的data,-1。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
    int data,id,next;
};
bool cmp(const node& n1,const node& n2){
    return n1.data<n2.data;
}
int main(){
    int n,s,id;
    cin>>n>>s;
    vector<node> vi(100000),res;
    for(int i=0;i<n;i++){
        cin>>id;
        cin>>vi[id].data>>vi[id].next;
        vi[id].id=id;
    }
    while(s!=-1){
        res.push_back(vi[s]);
        s=vi[s].next;
    }
    sort(res.begin(),res.end(),cmp);
    if(res.size()==0){
        printf("%d %d",res.size(),-1);
        return 0;
    }
    printf("%d %05d\n",res.size(),res[0].id);
    int i;
    for(i=0;i<res.size()-1;i++)
        printf("%05d %d %05d\n",res[i].id,res[i].data,res[i+1].id);
    printf("%05d %d %d\n",res[i].id,res[i].data,-1);
    return 0;
} 

转载于:https://www.cnblogs.com/A-Little-Nut/p/8334041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值