Examples: LinkedList: 1->2 , Head = 1 InsertAtTail(Head,1) ==> 1->2->1 InsertAtTail(Head,2) ==> 1->2->2 InsertAtTail(Head,3) ==> 1->2->3
This one is simple. Create a ListNode
node with the input data, interate over to the end of the list and append this new node to the end of the list by setting the next
pointer of the last node to point to the newly created node.
ListNode
- newNode
.
2. If head
is null, set head = newNode
.
3. If head
is not null, iterate to the last node of the list and set its next
pointer to newNode
.
4. Return head
.
public ListNode insertAtTail(ListNode head, int data) { }
C
Java
Python