PU Remove Linked List Elements

Jan 01, 1970

Remove all elements from a linked list of integers that have value val.

Example

  • Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
  • Return: 1 --> 2 --> 3 --> 4 --> 5

C Solution 1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode **p = &head;
    while (*p) {
        if ((*p)->val == val) {
            struct ListNode *tmp = (*p)->next;
            free(*p);
            *p = (*p)->next;
        }
        else p = &((*p)->next);
    }
    return head;
}

C Solution 2:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode dummy, *p = &dummy;
    p->next = head;
    while (p->next) {
        if (p->next->val == val) {
            head = p->next->next;
            free(p->next);
            p->next = head;
        }
        else p = p->next;
    }
    return dummy.next;
}

Python Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy = ListNode(0)
        dummy.next = head
        cur = dummy
        while cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next

Summary:

  1. 9ms, 25.69%
  2. If you need to find a node and then delete it, double pointer is what you want. Of course, you can use pre pointer, but that's not beautiful.

LeetCode: 203. Remove Linked List Elements