PAT A1052 Linked List Sorting (25分)

Insert picture description here

#include <cstdio>
#include <algorithm>

using namespace std;

struct Node{
    
    
	int address;
	int data;
	int next;
	int flag;
	Node(){
    
    
		flag = 0;
	}
}node[100010];

bool cmp(Node n1, Node n2){
    
    
	if(!(n1.flag==1 && n2.flag==1)){
    
    
		return n1.flag > n2.flag;
	}else{
    
    
		return n1.data < n2.data;
	}
}

int main(){
    
    
	int n, h;
	scanf("%d %d", &n, &h);
	
	int ad, da, ne;
	for(int i=0; i<n; i++){
    
    
		scanf("%d %d %d", &ad, &da, &ne);
		node[ad].address = ad;
		node[ad].data = da;
		node[ad].next = ne;
	}
	
	int count = 0;
	while(h != -1){
    
    
		count++;
		node[h].flag = 1;
		h = node[h].next;
	}
	
	if(count == 0){
    
    
		printf("0 -1");
		return 0;
	}
	
	sort(node, node+100010, cmp);
	
	printf("%d %05d\n", count, node[0].address);
	int i = 0;
	while(node[i].flag != 0){
    
    
		if(node[i+1].flag != 0){
    
    
			printf("%05d %d %05d\n", node[i].address, node[i].data, node[i+1].address);
		}else{
    
    
			printf("%05d %d -1\n", node[i].address, node[i].data);			
		}
		i++;
	}
	
	return 0;
} 

The idea of ​​this question is not difficult to think about, but it should be noted that the data with some test points may be on the linked list, so you need to traverse the linked list once and mark the nodes on the linked list.
Another thing to note is that if the given data are all invalid, that is, the linked list is empty, it needs to be judged to output "0 -1".

Guess you like

Origin blog.csdn.net/weixin_45964844/article/details/113090889