Linked List

A summary of linked list related problems from LeetCode with solutions in C++.

Problems:
203. Remove Linked List Elements
707. Design Linked List
206. Reverse Linked List
24. Swap Nodes in Pairs
19. Remove Nth Node From End of List
160. Intersection of Two Linked Lists
142. Linked List Cycle II

Example 1

Remove element 4 (credit to Carl)

Example 2

Remove element 1 with a dummy head node (credit to Carl)

Example 3

Add a linked list node (credit to Carl)

Example 4

Remove a linked list node (credit to Carl)

Example 5

Reverse a linked list (credit to Carl)

1. 203. Remove Linked List Elements

Problem: Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Case 1: Input: head = [1,2,6,3,4,5,6], val = 6, Output: [1,2,3,4,5]
Case 2: Input: head = [], val = 1, Output: []
Case 3: Input: head = [7,7,7,7], val = 7, Output: []

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

C++
class Solution1 {
public:
    ListNode* removeElements(ListNode* head, int val) {
        // delete head node
        while(head != nullptr && head->val == val) {
            ListNode* tmp = head;
            head = head->next;
            delete tmp;
        }
        // delete non-head node
        ListNode* cur = head;
        while(cur != nullptr && cur->next != nullptr) {
            if (cur->next->val == val) {
                ListNode* tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }
        return head;
    }
};

class Solution2 {
public:
    ListNode* removeElements(ListNode* head, int val) {
        // create a dummy head node
        ListNode* dummyHead = new ListNode(0);
        // make dummy head point to actually head
        dummyHead->next = head;
        ListNode* cur = dummyHead;
        while(cur != nullptr && cur->next != nullptr) {
            if (cur->next->val == val) {
                ListNode* tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }
        head = dummyHead->next;
        delete dummyHead;
        return head;
    }
};

2. 707. Design Linked List

Problem: Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.

Implement the MyLinkedList class:

(1) MyLinkedList() Initializes the MyLinkedList object.
(2) int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
(3) void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
(4) void addAtTail(int val) Append a node of value val as the last element of the linked list.
(5) void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
(6) void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.

Input:
[“MyLinkedList”, “addAtHead”, “addAtTail”, “addAtIndex”, “get”, “deleteAtIndex”, “get”]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output:
[null, null, null, null, 2, null, 3]
Explanation:
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3

// C++
class MyLinkedList {
public:
    // Assume all nodes in the linked list are 0-indexed.
    struct LinkedNode {
        int val;
        LinkedNode* next;
        LinkedNode (int val) : val(val), next(nullptr){}
    };
    // Init Linked list
    MyLinkedList() {
        _dummyHead = new LinkedNode(0);
        _size = 0;
    }
    // Add node at head
    void addAtHead(int val) {
        LinkedNode* newNode = new LinkedNode(val);
        newNode->next = _dummyHead->next;
        _dummyHead->next = newNode;
        _size++;
    }
    // Add node at tail
    void addAtTail(int val) {
        LinkedNode* newNode = new LinkedNode(val);
        LinkedNode* cur = _dummyHead;
        while(cur->next != nullptr) {
            cur = cur->next;
        }
        cur->next = newNode;
        _size++;
    }
    // Get value at index, invalid index return -1
    int get(int index) {
        // invalid index
        if(index > (_size-1) || index < 0) {
            return -1;
        }
        LinkedNode* cur = _dummyHead->next;
        while(index) {
            cur = cur->next;
            index--;
        }
        return cur->val;
    }
    // Add node before index(th) node
    void addAtIndex(int index, int val) {
        // Invalid index
        if(index > _size || index < 0) {
            return;
        }
        LinkedNode* newNode = new LinkedNode(val);
        LinkedNode* cur = _dummyHead;
        while(index) {
            cur = cur->next;
            index--;
        }
        newNode->next = cur->next;
        cur->next = newNode;
        _size++;
    }
    // Delete node at index 
    void deleteAtIndex(int index) {
        // Invalid index
        if(index >= _size || index < 0) {
            return;
        }
        LinkedNode* cur = _dummyHead;
        while(index) {
            cur = cur->next;
            index--;
        }
        LinkedNode* tmp = cur->next;
        cur->next = cur->next->next;
        delete tmp;
        _size--;
    }
    // Print linked list
    void printLinkedList() {
        LinkedNode* cur = _dummyHead;
        while(cur->next != nullptr) {
            cout << cur->next->val << " ";
            cur = cur->next;
        }
        cout << endl;
    }
private:
    int _size;
    LinkedNode* _dummyHead;
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList* obj = new MyLinkedList();
 * int param_1 = obj->get(index);
 * obj->addAtHead(val);
 * obj->addAtTail(val);
 * obj->addAtIndex(index,val);
 * obj->deleteAtIndex(index);
 */

3. 206. Reverse Linked List

Problem: Given the head of a singly linked list, reverse the list, and return the reversed list.

Case 1: Input: head = [1,2,3,4,5], Output: [5,4,3,2,1]
Case 2: head = [1,2], Output: [2,1]
Case 3: Input: head = [], Output: []

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 
// C++
class Solution1 {
public:
    // Double pointer method
    ListNode* reverseList(ListNode* head) {
        // Double pointers
        ListNode* tmp;
        ListNode* cur = head;
        ListNode* pre = nullptr;
        while(cur != nullptr) {
            // Save cur->next before override it
            tmp = cur->next;
            // Reverse operation
            cur->next = pre;
            // Update pre and cur
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

class Solution2 {
public:
    // Recursive method
    ListNode* reverse(ListNode*pre, ListNode* cur) {
        if(cur == nullptr) {
            return pre;
        }
        ListNode* tmp = cur->next;
        cur->next = pre;
        return reverse(cur, tmp);
    }
    // Call reverse() function
    ListNode* reverseList(ListNode* head) {
        // ListNode* pre = nullptr;
        // ListNode* cur = head;
        return reverse(nullptr, head);
    }
};

4. 24. Swap Nodes in Pairs

Problem: Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

Case 1: Input: head = [1,2,3,4], Output: [2,1,4,3]
Case 2: Input: head = [], Output: []
Case 3: Input: head = [1], Output: [1]

Hint:

Credit to Carl

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    // Time complexity: O(n)
    // Space complexity: O(1)
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* cur = dummyHead;
        while(cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* tmp1 = cur->next;
            ListNode* tmp2 = cur->next->next->next;
            // Step 1
            cur->next = cur->next->next;
            // Step 2
            cur->next->next = tmp1;
            // Step 3
            cur->next->next->next = tmp2;
            // Move two node for next pair
            cur = cur->next->next;
        }
        return dummyHead->next;
    }
};

5. 19. Remove Nth Node From End of List

Problem: Given the head of a linked list, remove the nth node from the end of the list and return its head.

Case 1: Input: head = [1,2,3,4,5], n = 2, Output: [1,2,3,5]
Case 2: Input: head = [1], n = 1, Output: []
Case 3: Input: head = [1,2], n = 1, Output: [1]

Hint:

Credit to Carl

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* slow = dummyHead;
        ListNode* fast = dummyHead;
        while(n && fast != nullptr) {
            fast = fast->next;
            n--;
        }
        // Move fast pointer one more step so that slow 
        // pointer points to the pre-node of the delete node
        fast = fast->next;
        while(fast != nullptr) {
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return dummyHead->next;
    }
};

6. 160. Intersection of Two Linked Lists

Problem: Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at node c1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns.

Case 1

Input:
intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output:
Intersected at ‘8’
Explanation:
The intersected node’s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. Note that the intersected node’s value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.

Case 2

Input:
intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output:
Intersected at ‘2’
Explanation:
The intersected node’s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.

Case 3

Input:
intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output:
No intersection
Explanation:
From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null.

Hint:

Credit to Carl

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* curA = headA;
        ListNode* curB = headB;
        int lenA = 0; 
        int lenB = 0;
        // Get length of linked list A
        while(curA != nullptr) {
            lenA++;
            curA = curA->next;
        }
        // Get length of linked list B
        while(curB != nullptr) {
            lenB++;
            curB = curB->next;
        }
        curA = headA;
        curB = headB;
        // Make curA the head of the longer linked list
        // and length of linked list A is lenA
        if(lenB > lenA) {
            swap(lenA, lenB);
            swap(curA, curB);
        }
        // Get difference of length
        int gap = lenA - lenB;
        // Make curA and curB at same start point
        // namely, the tails are aligned
        while(gap) {
            curA = curA->next;
            gap--;
        }
        // Traverse linked list A and B, till curA == curB
        while(curA != nullptr) {
            if(curA == curB) {
                return curA;
            }
            curA = curA->next;
            curB = curB->next;
        }
        return nullptr;
    }
};

7. 142. Linked List Cycle II

Problem: Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list.

Case 1

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Case 2

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Case 3

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Hint:

Credit to Carl

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast != nullptr && fast->next != nullptr) {
            fast = fast->next->next;
            slow = slow->next;
            // Fast pointer and slow pointer overlaps 
            // in the circle
            if(slow == fast) {
                ListNode* idx1 = fast;
                ListNode* idx2 = head;
                while(idx1 != idx2) {
                    idx1 = idx1->next;
                    idx2 = idx2->next;
                }
                // Return the entry of the cycle
                return idx1; 
            }
        }
        return nullptr;
    }
};

Back to top of page