Saturday, 18 April 2015

Hackerrank Delete a Node solution

Problem Statement

This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.

You’re given the pointer to the head node of a linked list and the position of a node to delete. Delete the node at the given position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The list may become empty after you delete the node.

Source code:

 /*  
  Delete Node at a given position in a linked list   
  Node is defined as   
  struct Node  
  {  
    int data;  
    struct Node *next;  
  }  
 */  
 Node* Delete(Node *head, int position)  
 {  
  // Complete this method  
   Node *cur;  
   cur = head;  
   if(position == 0){  
     head = head->next;  
   }else{  
     int i = 0;  
     while(cur!= NULL){  
       if(i == (position)-1){  
         cur -> next = (cur->next)->next;  
         break;  
       }else{  
       cur = cur->next;  
       }  
       i++;  
     }  
   }  
   return head;  
 }  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

3 comments:

  1. Majority of students feel nervous and lose confidence when they are asked for writing some essays and presenting before others. If you are one of them then kick away this condition by getting the excellent Best essay writing service ever for preparing your papers without mistakes and within your cost.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Every code is very clear and easy thank you

    ReplyDelete