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
解题思路:
- 理解题意:主要的一点,存在无效结点,在PTA中的链表题好像都存在这无效结点作为干扰
- 代码思路:要判断结点是否有效,用while(saddress!=-1)来判断;然后从cmp()函数,让false的然后排,true的让前排,也就是说,有效结点让前排。
- 总结:①要特判0 -1的情况;②cmp的排序是排序整个数组,不是仅排序有效数组;③用node[address]这个方式sort排序的时候,要注意,要把他原先的address赋给他的结构体变量node[i].address,因为排序后,node[i]会变化,如从11111变为0;
代码:
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=100010;
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{
return a.data<b.data;
}
}
int main(){
for(int i=0;i<maxn;i++){
node[i].flag=false;
}
int n,saddress;
scanf("%d %d",&n,&saddress);
for(int i=0;i<n;i++){
int add;
scanf("%d",&add);
scanf("%d %d",&node[add].data,&node[add].next);
node[add].address=add;
}
int count=0;
while(saddress!=-1){ //找到有效节点
node[saddress].flag=true;
saddress=node[saddress].next;
count++;
}
if(count==0){ //特判没有有效节点
printf("0 -1\n");
}
else{
sort(node,node+maxn,cmp); //错的结点
printf("%d %05d\n",count,node[0].address);
for(int i=0;i<count-1;i++){
printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address); //不能使用node[i].next,因为next没有变动,但是实际node[i].next已经变动了
}
printf("%05d %d -1",node[count-1].address,node[count-1].data);
}
return 0;
}