Sunday, February 25, 2018

C program : To delete all but the last N elements from the linked list, and print the resulting list.



You are given a sequence of integers terminated with a -1. The -1 is
not part of the input sequence.

Next, you are given a positive number N.

You have to create a linked list with the input sequence of integers
as entries.

Now, you have to delete all but the last N elements from the linked
list, and print the resulting list. (i.e. The resulting list will
consist of only the last N elements from the list.)


If N is longer than the length of the linked list, you must print -1.

While printing, the entries of the list must be separated by a single
space.

You can use the following structure.

 struct node{
  int data;
struct node *next;
 };

Sample Input
3 4 5 6 -1
1

Sample Output
6
// C program to find n'th node in linked list
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};

/* Given a reference (pointer to pointer) to the head
    of a list and an int, push a new node on the front
    of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
            (struct Node*) malloc(sizeof(struct Node));

    /* put in the data  */
    new_node->data  = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

/* Takes head pointer of the linked list and index
    as arguments and return data at index*/
int GetNth(struct Node* head, int index)
{
    struct Node* current = head;
    int count = 0; /* the index of the node we're currently
                  looking at */
    while (current != NULL)
    {
       if (count == index)
          return(current->data);
       count++;
       current = current->next;
    }

    /* if we get to this line, the caller was asking
       for a non-existent element so we assert fail */
    assert(0);
}

/* Drier program to test above function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;

    /* Use push() to construct below list
     1->12->1->4->1  */

      int n=0,N=0,j=0;
      while(n!=-1)
{

      scanf("%d",&n);
    push(&head, n);
    j+=1;

}
   scanf("%d",&N);
    /* Check the count function */
  if(N<j)
{
    for(int i=0;i<N;i++)
    { 
      printf("%d ", GetNth(head, N-i));
     
    }
}
  else{printf("-1");}
}

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows