zoukankan      html  css  js  c++  java
  • 【LeetCode】203. Remove Linked List Elements

    题目:

    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;
    }
  • 相关阅读:
    如果世界变慢为原先的百万分之一
    N880e 刷机记录和一些经验
    Linux Shell Commands 常用Linux命令行
    适用于单选的jQuery Autocomplete插件SelectToAutocomplete
    PHP5.3 中的Warning: date_default_timezone_set
    Apache中RewriteCond规则和QUERY_STRING参数
    网站网络编辑日常工作流程
    网站编辑与传统媒体编辑的区别及特点
    使用JCaptcha生成验证码
    Debian 7 Wheezy 安装Oracle JDK6, JDK5和Tomcat6
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6758994.html
Copyright © 2011-2022 走看看