linked list Interview Question

Insert Node at nth position in a linked list

You’re given the pointer to the head node of a linked list, an integer to add to the list & the position at which the integer must be inserted. Create a new node with the given integer, insert this node at the desired position and return the head node. A position of zero indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.
Input FormatYou have to complete the Node Insert(Node* head, int data, int position) method which takes three arguments the head of the linked list, the integer to insert and the position at which the integer must be inserted. You should NOT read any input from stdin/console. position will always be between 0 and the number of the elements in the list.
Output FormatInsert the new node at the desired position and return the head of the updated linked list. Do NOT print anything to stdout/console.
Sample Input
NULL, data = 3, position = 0
3 --> NULL, data = 4, position = 0
Sample Output
3 --> NULL
4 --> 3 --> NULL
Explanation
- we have an empty list and position 0. 3 becomes head.
- 4 is added to position 0, hence 4 becomes head.
Node* InsertNth(Node *head, int data, int position) { // Complete this method only // Do not write main function. struct Node* newnode = (struct Node*)malloc(sizeof(struct Node*)); newnode->data=data; newnode->next=NULL; struct Node* ptr = head; if(ptr==NULL) { head = newnode; return head; } else if(position==0) { newnode->next=head; head=newnode; return head; } else { while(position>1) { ptr=ptr->next; position--; } if(ptr->next==NULL) { ptr>next=newnode; } else { newnode>next=ptr->next; ptr->next=newnode; } return head; } }
Note that this approach is not only specific to this type of question you can use this sorting technique in various questions such as if you want to check whether to word are anagrams of one another or not. You can simply sort them and compare them to find out. This approach is also helpful in other questions so i suggest that its better to learn this tricks and keep in mind while attempting the question you may find it useful. You can always search for more coding problems like this to get comfortable to this to approach or you can find new problems where this approach is applicable. So go and search more problems like this and check whether this approach is useful or not and you can tell me about it by commenting and writing about this to me.
Try more and more problems that you find on string and arrays and try to develop an approach the will help you understand problems rather then learning the solution. Once you know how to approach the problem you will able to solve any problem related to strings and array. I wish best of luck to you for your future.
0 comments:
Post a Comment