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(" ");
}
}
}