Member-only story
Leetcode Top Linked List exercises (Easy)
This is a compilation of linked list exercises, in this post we will only tackle easy exercises to get familiar on how to use linked list and get comfortable using them in Java.
Exercises tackled in this post (Please contact me with suggestions if you want some more added there):
- Merge Two Sorted Lists
- Remove Duplicates from Sorted List
- Remove Linked List Elements
- Linked List Cycle
Linked list definition
In all Leetcode exercises, linked lists are defined using the ListNode class:
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
In most cases, we will be given just one ListNode called head, which is the head of the list, and we can access the other elements by calling head.next, head.next.next, etc.
Linked list are defined recursively, since the next pointer in the ListNode is a ListNode. This will help in many cases when trying to implement solutions recursively.
Merge Two Sorted Lists
In this exercise we have 2 sorted linked lists list1 and list2, and we want to return a sorted list containing all the elements from list1 and list2.