Sunday, 29 November 2015

Insert a node at the tail of a linked list

Problem Statement
You’re given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer, insert this node at the tail of the linked list and return the head node. The head pointer given may be null meaning that the initial list is empty.
Input Format 
You have to complete the Node* Insert(Node* head, int data) method which takes two arguments - the head of the linked list and the integer to insert. You should NOT read any input from stdin/console.
Output Format 
Insert the new node at the tail and just return the head of the updated linked list. Do NOT print anything to stdout/console.
Sample Input
NULL, data = 2
2 --> NULL, data = 3
Sample Output
2 -->NULL
2 --> 3 --> NULL
Explanation 
1. We have an empty list and we insert 2.
2. We have 2 in the tail, when 3 is inserted 3 becomes the tail.

1
/*
2
  Insert Node at the end of a linked list 
3
  head pointer input could be NULL as well for empty list
4
  Node is defined as 
5
  struct Node
6
  {
7
     int data;
8
     struct Node *next;
9
  }
10
*/
11
Node* Insert(Node *head,int data)
12
{
13
  // Complete this method
14
    Node* node = (Node*)malloc(sizeof(Node));
15
    node->data = data;
16
    Node* temp = head;
17
    node->next = NULL;
18
    if(head == NULL){
19
        head = node;
20
    }else{
21
        while(temp->next != NULL){
22
            temp = temp->next;
23
        }
24
        temp->next = node;
25
    }
26
    return head;
27
}

No comments:

Post a Comment