203. Remove Linked List Elements *

  • Total Accepted: 99807
  • Total Submissions: 319528
  • Difficulty: Easy
  • Contributors: Admin

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

分析


方法一 迭代 recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * 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 || head->next == NULL && head->val != val) return head;
         
        if(head->val == val){
            return removeElements(head->next, val);
        }
        else{
            head->next = removeElements(head->next, val);
            return head;
        }
    }
};

方法二 

使用双指针,移相删除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 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 || head->next == NULL && head->val != val) return head;
         
        ListNode dummy(-val);
        ListNode *pre = &dummy, * cur = head;
        dummy.next = head;
        while(cur){
            if(cur->val == val){
                pre->next = cur->next;
                cur = cur->next;
            }
            else{
                pre = cur;
                cur = cur->next;
            }
        }
        return dummy.next;
    }
};

方法三

使用指向指针的指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == NULL || head->next == NULL && head->val != val) return head;
         
        //consider head is a Node's next
        ListNode ** p = &head;
         
        while(*p){
            if((*p)->val == val){
                (*p) = (*p)->next;
            }
            else{
                p = &(*p)->next;
            }
        }
        return head;
    }
};




posted @ 2017-02-20 15:30  copperface  阅读(175)  评论(0编辑  收藏  举报