Given a singly-linked list, implement a method to insert a node at a specific position and return the head of the list.
If the given position is greater than the list size, simply insert the node at the end.
Input List: 1->2->3
insertAtPosition(1,4,2) ==> 1->4->2->3
Node
and insert it after traversing to the desired position. Remember that the List
can also be empty.
1. Create new ListNode N
2. If head
is null
, set head = N
3. Otherwise, traverse to the last node of the list while current != null
4. Keep track of previous node and current position in the list while traversing through the list
5. If the current position == pos
, set previous.next = N; N.next = current; break;
6. Return head
public ListNode insertAtPosition(ListNode head, int data, int pos) { }
C
Java
Python