前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pat 1052 Linked List Sorting (25)

Pat 1052 Linked List Sorting (25)

作者头像
ShenduCC
发布2018-04-26 17:05:21
5210
发布2018-04-26 17:05:21
举报
文章被收录于专栏:算法修养算法修养

1052. Linked List Sorting (25)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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:

代码语言:javascript
复制
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345

Sample Output:

代码语言:javascript
复制
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
巨坑,有链表是空的情况,还有点不再链表中,还有千万别用cin#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include <map>

using namespace std;
#define MAX 100000
struct Node{
    char l[10],r[10];
    int key;
}a[MAX+5],e[MAX+5];
int cmp(Node a,Node b){
    return a.key<b.key;
}
int n;
char b[10];
map<string,string> m1;
map<string,int> m2;
int main()
{
	scanf("%d",&n);scanf("%s",b);
    m1.clear();m2.clear();
    for(int i=1;i<=n;i++){
		scanf("%s%d%s",a[i].l,&a[i].key,a[i].r);
        m1[a[i].l]=a[i].r;m2[a[i].l]=i;
    }
	string c=b;
    if(c=="-1"){
        cout<<0<<" "<<b<<endl;
        return 0;
    }
	int cnt=0;
    while(c!="-1"){
      e[++cnt]=a[m2[c]];
	  c=m1[c];
    }
    sort(e+1,e+cnt+1,cmp);
    cout<<cnt<<" "<<e[1].l<<endl;
    for(int i=1;i<=cnt-1;i++)
        cout<<e[i].l<<" "<<e[i].key<<" "<<e[i+1].l<<endl;
    cout<<e[cnt].l<<" "<<e[cnt].key<<" "<<"-1"<<endl;
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-04-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1052. Linked List Sorting (25)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档