Problem
List the last n nodes
Solution
#include <iostream>
using namespace std;
typedef struct linked_list{
int data;
struct linked_list *next;
}Linked_list;
int add_node(Linked_list **head, int d)
{
Linked_list *l = new Linked_list;
if(l == NULL) return 0;
Linked_list *t = *head;
l->data = d;
l->next = NULL;
if(*head == NULL){
*head = l;
return 1;
}
while(t->next != NULL){
t = t->next;
}
t->next = l;
return 1;
}
void list_last_n_elements(Linked_list *head, Linked_list **lastn, int n)
{
int k = 0;
Linked_list *l = head;
if(head == NULL){
*lastn = NULL;
return;
}
*lastn = head;
while(l!=NULL){
if(k < n){
k++;
}
else{
(*lastn) = (*lastn)->next;
}
l=l->next;
}
}
void delete_list(Linked_list *head)
{
while(head != NULL){
Linked_list *t = head->next;
delete head;
head = t;
}
}
int main(int argc, char* argv[])
{
Linked_list *head = NULL;
Linked_list *l;
add_node(&head, 1);
add_node(&head, 1);
add_node(&head, 2);
add_node(&head, 3);
add_node(&head, 9);
add_node(&head, 4);
add_node(&head, 1);
add_node(&head, 5);
cout << "before" << endl;
l = head;
while(l!=NULL){
cout << l->data << endl;
l = l->next;
}
Linked_list *lastn;
for(int i = 0; i < 3; i ++){
cout << "last " << i << " in the list " << endl;
list_last_n_elements(head, &lastn, i);
l = lastn;
while(l!=NULL){
cout << l->data << endl;
l = l->next;
}
}
delete_list(head);
return 0;
}
Output
before
1
1
2
3
9
4
1
5
last 0 in the list
last 1 in the list
5
last 2 in the list
1
5