7-2 Rank a Linked List分数 25

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<iostream>
using namespace std;
const int N = 100010;
int n;
int e[N],ne[N];
bool has_pre[N];
int main(){
    scanf("%d",&n);
    for(int i = 0;i<n;i++){
        int next;scanf("%d",&next);
        ne[i] = next;
        has_pre[next] = true;
    }
    int h = 0;
    while(has_pre[h])h++;
    int k = 1;
    for(int i = h;~i;i=ne[i]){
        e[i] = k++; 
    }
    printf("%d",e[0]);
    for(int i = 1;i<k;i++){
        printf(" %d",e[i]);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值