301. Insert a Node at the End

EasyLinked ListLinked ListInsertion

Given the head of a singly linked list and an integer val, append a new node with value val at the end of the list and return the head.

Traverse to the last node, then attach the new node.

Input: Head of a singly linked list and an integer val.

Output: Head of the updated linked list with new node appended at the end.

Examples

Example 1
Input: [1,2,3,4], 5
Output: [1,2,3,4,5]
Explanation: Traverse to node(4). Set node(4).next = new node(5). Return head(1). Result: 1→2→3→4→5.
Example 2
Input: [10,20], 30
Output: [10,20,30]
Explanation: Traverse to node(20). Attach node(30). Return head(10). Result: 10→20→30.
Example 3
Input: [7], 8
Output: [7,8]
Explanation: Node(7) is both head and tail. Attach node(8). Result: 7→8.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →