PAT(甲级)2021年冬季考试 7-2 Rank a Linked List

本文介绍了一种通过链表结构实现节点排名的算法,并详细解释了如何存储链表及确定每个节点的位置。输入包含链表的节点数及其连接方式,输出为各节点按顺序排列的排名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

7-2 Rank a Linked List
分析:
题意比较清楚简单,创建一个链表结构,记录结点的下一个结点和位置即可。

A linked list of n nodes is stored in an array of n elements. Each element contains an integer data and a next pointer which is the array index of the next node. It is guaranteed that the given list is linear – that is, every node, except the first one, has a unique previous node; and every node, except the last one, has a unique next node.

Now let’s number these nodes in order, starting from the first node, by numbers from 1 to n. These numbers are called the ranks of the nodes. Your job is to list their ranks.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive number n (≤105) which is the total number of nodes in the linked list. Then n numbers follow in the next line. The ith number (i=0,⋯,n−1) corresponds to next(i) of the ith element. The NULL pointer is represented by −1. The numbers in a line are separated by spaces.

Output Specification:
List n ranks in a line, where the ith number (i=0,⋯,n−1) corresponds to rank(i) of the ith element. The adjacent numbers in a line must be separated by exactly 1 space, and there must be no extra space at the beginning or the end of the line.

Sample Input:
5
3 -1 4 1 0
Sample Output:
3 5 1 4 2
Hint:
The given linked list is stored as 2->4->0->3->1->NULL. Hence the 0th element is ranked 3 since it is the 3rd node in the list; the 1st element is ranked 5 since it is the last (the 5th) node in the list; and so on so forth.
代码

#include<stdio.h>

const int maxn = 100010;
struct Node{
    int next;
    int pos;
}node[maxn];

int main(){
    int n, head, temp[maxn];
    bool vis[maxn] = {false};
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d", &node[i].next);
        if(node[i].next != -1){
            vis[node[i].next] = true;
        }
        temp[i] = node[i].next;
    }
    for(int i = 0; i < n; i++){
        if(vis[i] == false){
            head = i;
            break;
         }
    }
    int newnode = head;
    int count = 0;
    while(node[newnode].next != -1){
        node[newnode].pos = count++;
        newnode = node[newnode].next;
    }
    node[newnode].pos = count++;
    for(int i = 0; i < n; i++){
    	if(temp[i] != -1){
    		printf("%d", node[temp[i]].pos);
		}else{
			printf("%d", n);
		}
        
        if(i < n - 1){
            printf(" ");
        }
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值