[LeetCode 解题报告]203. Remove Linked List Elements

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Method 1.

/**
 * 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;
        
        head->next = removeElements(head->next, val);
        if (head->val == val)
            return head->next;
        else
            return head; 
    }
};

Method 2.

/**
 * 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* dummy = new ListNode(-1);
        dummy->next = head;
        
        ListNode* cur = dummy;
        while (cur->next) {
            if (cur->next->val == val) {
                ListNode* temp = cur->next;
                cur->next = temp->next;
                temp->next = NULL;
                delete temp;
            }
            else
                cur = cur->next;
        }
        return dummy->next;
    }
};
发布了467 篇原创文章 · 获赞 40 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104158935
今日推荐