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 分)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?