Crimes are frequent in a planet far away from earth. So the people there have decided to form a
police force and they want the oldest five persons to be the police officers. Because there are many people in this village, they want you to write a program to find the oldest five.
Input (police.in)
1. First line contains N (5 <= N <= 1000).
2. Each of the next N lines contains Ai which is the age of the ith person. The ID number of
the ith person is also ‘i’.
Output (police.out)
Example Input
10
10
3
20
100
50
11
15
25
60
75
Example Output
4
10
9
5
8
2,531 Views |
1) Take each input from the file. and for the first five items put it in a linked list. head pointer points to the start of the list and last pointer points to the fifth element.
2) when iteration starts from the 6th element, compare the age of the ith element to the age pointed by the “last” pointer. if it is greater, free the “last” pointer and update it to the previous
3) try to insert the ith node to the existing 4 element linked list and update the “last” pointer accordingly so that it points to the last element of the list.
Eg:
//get the input from the file..
int temp;
int N = getinputfromFile ( ) //some file operation to read inputs from file.
struct list *ageArr = NULL;
strcut list *head = NULL;
struct list *last = NULL;
struct list *tmpLast = NULL;
strcut list *tmpArr = NULL;
for ( i= 1; iage = getInputFromFile();
tmpArr->index= i;
tmpArr->next = NULL;
if (ageArr == NULL ) {
head = ageArr;
ageArr = tmpArr;
ageArr->prev = NULL;
else {
ageArr = head;
while (tmpArr->age age ) {
if(ageArr->next != NULL)
ageArr = ageArr->next;
else break;
}
ageArr->next =tmpArr;
ageArr->next->prev = ageArr
ageArr = ageArr->next;
}
}
last = ageArr;
for (i=6; i last->age) {
last= last->prev;
last->next->prev = NULL;
free(last->next);
last->next = NULL;
tmpArr= malloc (sizeof(struct list));
tmpArr->age = temp;
tmpArr->index= i;
tmpArr->next = NULL;
while(last->age prev;
}
if (last == NULL) {
tmpArr->next = head;
tmpArr->prev= NULL;
head->prev = tmpArr;
head = tmpArr;
}
else {
tmpArr->next = last->next;
last->next = tmpArr;
tmpArr->next->prev = tmpArr;
tmpArr->prev = last;
}
if (tmpLast == NULL) last = tmpArr;
else last = tmpLast;
}
}
}
Leave an Answer/Comment