C++ clean code sharing, 36ms, iteration, two pointer


  • 0
    S
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode dummy(-1);
            dummy.next = head;
            ListNode* prev = &dummy;
            ListNode* cur = head;
            while(cur != NULL) {
                if(cur->val == val) {
                    cur = cur->next;
                    prev->next = cur;
                } else {
                    cur = cur->next;
                    prev = prev->next;
                }
            }
            return dummy.next;
        }
    };

  • 0
    H

    I have similar idea but a little bit cleaner code.

    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode dummy(-1);
            dummy.next = head;
            ListNode *p = &dummy;
            while (p && p->next) {
                if (p->next->val == val) 
                    p->next = p->next->next;
                else
                    p = p->next;
            }
            return dummy.next;
        }
    };

  • 0
    N

    this doesn't free up space?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.