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;
    }
  • 相关阅读:
    css盒子模型之内边距padding及简写
    css盒子模型之宽度和高度
    windows 组策略
    windows 快捷键
    cmd 命令快捷键
    django 远程访问
    django 部署在 apache2 上面
    国内常用开源镜像站
    ubuntu1804自带官方源
    ubuntu1604 apt华为国内源
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6758994.html
Copyright © 2011-2022 走看看