Keep the First K Nodes
Cut the list after its first k nodes and return the head. If the list has k nodes or fewer, return it unchanged. When k is 0 the result is empty. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
head [1,2,3,4,5]
k 3
returns [1,2,3]
Only 1, 2, 3 stay.
Example 2
head [1,2]
k 5
returns [1,2]
Shorter than k, so nothing is cut.
Constraints
0 <= number of nodes <= 100-100 <= Node.val <= 1000 <= k <= 200
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.