【PAT】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 FORMAT

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.

翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一行包括一个正整数N(< 10^5)和一个头结点地址,N代表存储中点的总数,节点地址为一个5位数字的正整数。NULL用-1表示。
接着N行每行以以下格式描述一个节点:
地址 键值 下一节点
Address代表存储中的节点地址,键值为一个 [-105, 105]的正整数,Next是下一个节点的地址。数据保证所有的键值是唯一的并且从头结点开始无环。

OUTPUT FORMAT

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.

翻译:对于每组输入数据,按照样例输入的格式输出,N为链表中节点的个数,所有节点以排序后的顺序输出。


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


解题思路

这道题注意先搜一遍链表,有些点不在链表上。。还有,如果链表长度为0,输出0 -1,即S为-1的情况。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
using namespace std;
int N,S;
struct Node{
    int data,id,next;
    bool operator<(const Node &a)const{
        return data<a.data;
    }

};
vector<Node> v; 
Node G[100010];
int main(){
    scanf("%d%d",&N,&S);
    int a,b,c;
    for(int i=0;i<N;i++){
        scanf("%d%d%d",&a,&b,&c);
        G[a].id=a;
        G[a].data=b;
        G[a].next=c;
    }
    while(S!=-1){
        v.push_back(G[S]);
        S=G[S].next;
    }
    sort(v.begin(),v.end());
    if(v.size()>0)
    printf("%d %05d\n",v.size(),v[0].id);
    else printf("0 -1\n");
    for(int i=0;i<v.size();i++){
        if(i==v.size()-1)printf("%05d %d -1\n",v[i].id,v[i].data);
        else printf("%05d %d %05d\n",v[i].id,v[i].data,v[i+1].id);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值