We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Insert a node at a specific position in a linked list
Insert a node at a specific position in a linked list
Sort by
recency
|
1492 Discussions
|
Please Login in order to post a comment
Great stuff, I am very thanksfull for your great information. Could you please have a look on my site recommend me the best way to isert linklist on my site Best Product Reviews Awaiting for your kind response.
My Python solution, suggestions for improvement welcome:
SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) { if (llist != NULL) { SinglyLinkedListNode *before, *tempList, *newNode = new SinglyLinkedListNode(data); tempList = llist; for (int i = 1; i < position; i++) {tempList = tempList->next;} newNode->next = tempList->next; tempList->next = newNode; return llist; } else { return new SinglyLinkedListNode(data);} }
go golang solution
// Insert a node at a specific position in a linked list // JAVA Solution
if(llist == null){ if(position==1) return new SinglyLinkedListNode(data); } if(position==1){ SinglyLinkedListNode temp = new SinglyLinkedListNode(data); return temp; } SinglyLinkedListNode curr = llist; int count = 0; while(curr != null){ if(count == position-1){ SinglyLinkedListNode temp = new SinglyLinkedListNode(data); temp.next = curr.next; curr.next = temp; break;
} count++; curr = curr.next; } return llist;