Search This Blog

Wednesday, January 1, 2014

Algorithm - Linked Lists - Insert a node at a specific position in a linked list

Insert a node at a specific position in a linked list

The following is the solution to Hacker Rank problem Insert a node at a specific position in a linked list using Java.  For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.

Score: 5/5
Node* InsertNth(Node *head, int data, int position)
{
  // Complete this method only
  // Do not write main function.
 
    Node *newNode = new Node();
    newNode->data = data;
    newNode->next = NULL;
    Node *temp = head;
 
    if(position == 0)
    {
        newNode->next = head;
        head = newNode;
    }
    else
    {
        for(int i = 1; i < position; i++)
            temp = temp->next;
        newNode->next = temp->next;
        temp->next = newNode;
    }
    return head;
}

Algorithm - Linked Lists - Delete a node from a linked list

Delete a node from a linked list

The following is the solution to Hacker Rank problem Delete a node from a linked list using Java.  For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.

Score: 5/5
Node* Delete(Node *head, int position)
{
    // Complete this method
    Node *temp = head;
    if(position == 0)
        head = head->next;
    else
    {
        for(int i = 1; i < position; i++)
            temp = temp->next;
        Node *del = temp->next;
        temp->next = del->next;
    }
    return head;
}

Algorithm - Linked Lists - Print the elements of a linked list in reverse

Print the elements of a linked list in reverse

The following is the solution to Hacker Rank problem Print the elements of a linked list in reverse using Java.  For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.

Score: 5/5
void ReversePrint(Node *head)
{

  if(head == NULL)
    return;
   
  // traverse the list
  ReversePrint(head->next);

//print the element
  printf("%d\n", head->data);
}

Labels