0
点赞
收藏
分享

微信扫一扫

1052 Linked List Sorting (25 分) 简单链表模拟 千万注意地址输出百分之05d

我阿霆哥 2022-09-19 阅读 263


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 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 [−10​5​​,10​5​​], 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

很简单,又是卡在地址输出上,第一行的首地址输出用cout了。。唉!以后涉及链表的输入输出都用scanf和printf吧

本题唯一需要注意的就是链表未空,给的首地址根本没出现过,此时输出0 -1

#include<bits/stdc++.h>
using namespace std;
struct Node{
int address,key,next;
}node[100010],ans[100010];
bool compare(Node a,Node b){
return a.key<b.key;
}
int n,h;
int main(){
// freopen("in.txt","r",stdin);
cin>>n>>h;
int add,key,next;
while(n--){
cin>>add>>key>>next;
node[add].address=add;
node[add].key=key;
node[add].next=next;
}
n=0;
for(int i=h;i!=-1;i=node[i].next){//最好这么遍历一遍而不直接排序 防止输入的有垃圾结点
ans[n++]=node[i];
}
//特判,h给的特别不好,根本就不存在,此时为空
if(n==0){
cout<<"0 -1";
return 0;
}
sort(ans,ans+n,compare);
// cout<<n<<" "<<ans[0].address<<"\n";//又是地址输出问题。。
printf("%d %05d\n",n,ans[0].address);
for(int i=0;i<n;i++){
printf("%05d %d ",ans[i].address,ans[i].key);
if(i==n-1) cout<<"-1\n";
else printf("%05d\n",ans[i+1].address);
}
return 0;
}

链表题总结:1.注意没用的结点(连不起来的点) 最最后的长度可能不是原始的n了,排序时注意+n   
            2.简单模拟  不需要写复杂的增删改查   都是难度较低的25分题 
            3.地址是5位整数  输出千万别忘记%05d  

举报

相关推荐

0 条评论