203. Remove Linked List Elements

来源:互联网 发布:java web九九乘法表 编辑:程序博客网 时间:2024/05/16 17:38

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

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.


添加dummy头结点,简化代码书写

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* removeElements(ListNode* head, int val) {        if(!head)            return NULL;        ListNode *dummy = new ListNode(INT_MAX);        dummy->next = head;        ListNode *prev = dummy;        ListNode *cur = head;        while(cur)        {            if(cur->val != val)            {                cur = cur->next;                prev = prev->next;            }            else            {                prev->next = cur->next;                delete cur;                cur = prev->next;            }        }                return dummy->next;    }};



/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* removeElements(ListNode* head, int val) {        if(head == NULL)            return NULL;                ListNode *res = head;        ListNode *p = head;                //处理末尾相等的情况        while(p && p->val == val)        {            ListNode *tmp = p;            p = p-> next;            delete tmp;        }                res = p;                //处理中间相等的情况        while(p)        {            if(p -> next && p->next->val == val)            {                ListNode *tmp = p->next;                p->next = p->next->next;                delete tmp;                continue;            }                        p=p->next;        }                return res;    }};


0 0
原创粉丝点击