You are viewing a single comment's thread. Return to all comments →
Another flavor, with an extra short circuit check and a while loop. This handles pathological cases better (like position > length of list):
def InsertNth(head,data,position): if head is None or position == 0: return Node(data,head) else: cur_pos = 1 cur_node = head while cur_node.next and cur_pos < position: cur_node = cur_node.next cur_pos += 1 cur_node.next = Node(data,cur_node.next) return head
Seems like cookies are disabled on this browser, please enable them to open this website
Insert a node at a specific position in a linked list
You are viewing a single comment's thread. Return to all comments →
Another flavor, with an extra short circuit check and a while loop. This handles pathological cases better (like position > length of list):