203. Remove Linked List Elements -- version 2

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ // This node has some memory leak class Solution { public: ListNode* removeElements(ListNode* head, int val) { if (head == nullptr) return head; while((head->val == val) && head != nullptr){ head = head->next; if (head == nullptr) return head; } // else ListNode * prev = head; ListNode * curr = head->next; while(curr != nullptr){ if (curr->val == val){ prev->next = curr->next; curr = curr->next; } else{ prev = curr; curr = curr->next; } } return head; } };
Many edge cases.... Need to check the logic of my code.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.