LeetCode203 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

题源:here

思路:

这道题就是很简单的遇到目标数然后删除就行了,但是再实现上面可以有区别。例如,第一种解法使用的两个相邻的指针,这样我们的删除操作会简单很多;第二种方式只用了一个指针,但是再删除元素时需要更小心的处理边界元素。

解法1

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode feakHead(0);
        feakHead.next = head;
        ListNode *pre, *curr;
        pre = &feakHead, curr = head;
        while(curr){
            if(curr->val == val) pre->next = curr->next;
            else pre = pre->next;    
            curr = curr->next;
        }
        return feakHead.next;
    }
};

解法2

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

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88621045
今日推荐