码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】203. Remove Linked List Elements

时间:2017-04-24 23:07:02      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:amp   elements   rem   print   code   link   没有   导致   false   

题目:

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

题解:

   这道题没什么好讲的,基础操作。需要注意的是链表的第一个node,因为没有前驱节点,所以该node需要特殊处理,会导致额外的代码量。如果创建一个dummy,将其作为第一个node的前驱节点,这样链表中所有的node都可以也能够同样的逻辑来处理了。

Solution 1 ()

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        static ListNode dummy(-1);
        dummy.next = head;
        ListNode *p = &dummy;
        
        while( p->next) {
            if (p->next->val == val) {
                p->next = p->next->next;
            }else{
                p = p->next;
            }
        }
        
        return dummy.next;
    }
};

  这里有个技巧,利用二级指针,操作简洁

Solution 2 ()

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode **r = &head;
        while(*r != NULL) {
            if((*r)->val == val) {
                *r = (*r)->next;
            }else {
                r = &(*r)->next;
            }
        }
        return head;        
    }
};

  还有一种递归的思想

Solution 3 ()

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
};

 最后附上创建链表和打印链表的函数

CreatList

ListNode* createList(vector<int> nums) {
    ListNode *head = NULL, *p = NULL;
    int n = nums.size();
    for(int i=0; i<n; ++i) {
        if(head == NULL) head = p = new ListNode(nums[i]);
        else {
            p->next = new ListNode(nums[i]);
            p = p->next;
        }
    }
    return head;
}

PrintList

void printList(ListNode *head) {
    ListNode *p = head;
    while(p) {
        if(p == head && p) {
            cout << p->val;
            p = p->next;
        }else {
            cout  << "->" << p->val;
            p = p->next;
        }
    }
    delete p;
    cout<<endl;
}

 

【LeetCode】203. Remove Linked List Elements

标签:amp   elements   rem   print   code   link   没有   导致   false   

原文地址:http://www.cnblogs.com/Atanisi/p/6758994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!