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
+ 0 comments Python 3:
def insertNodeAtPosition(llist, data, position):
nd = SinglyLinkedListNode(data) if position == 0: nd.next = llist return nd else: prev = llist nx = llist.next while position > 1: position -= 1 prev = prev.next nx = nx.next prev.next = nd nd.next = nx return llist
+ 0 comments Java:
public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) { SinglyLinkedListNode preNode = llist; for(int i = 0; i < position - 1; i++){ preNode = preNode.next; } SinglyLinkedListNode node = new SinglyLinkedListNode(data); node.next = preNode.next; preNode.next = node; return llist; }
+ 0 comments new_node = SinglyLinkedListNode(data) nodes = [] node = llist while node: nodes.append(node) node = node.next new_node.next = nodes[position - 1].next nodes[position - 1].next = new_node return nodes[0]
+ 0 comments Python Solution:
def insertNodeAtPosition(llist, data, position): new_node = SinglyLinkedListNode(data) nodes = [] node = llist while node: nodes.append(node) node = node.next new_node.next = nodes[position - 1].next nodes[position - 1].next = new_node return nodes[0]
+ 0 comments My Go(Golang) solution
var node *SinglyLinkedListNode node = &SinglyLinkedListNode{data, nil} var currentNode *SinglyLinkedListNode = llist var prevNode *SinglyLinkedListNode = nil for i := 0; int32(i) <= position; i++{ if int32(i) == position{ prevNode.next = node node.next = currentNode } else{ prevNode = currentNode currentNode = currentNode.next } } return llist
Load more conversations
Sort 33 Discussions, By:
Please Login in order to post a comment