zoukankan      html  css  js  c++  java
  • #Leetcode# 203. Remove Linked List Elements

    https://leetcode.com/problems/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

    递归代码:

    /**
     * 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) return NULL;
            head -> next = removeElements(head -> next, val);
            return head -> val == val ? head -> next : head;
        }
    };
    View Code

    非递归代码:

    /**
     * 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) {
            ListNode *dummy = new ListNode(-1), *pre = dummy;
            dummy -> next = head;
            while(pre -> next) {
                if(pre -> next -> val == val) {
                    ListNode *t = pre -> next;
                    pre -> next = t -> next;
                    t -> next = NULL;
                    delete t;
                }
                else pre = pre -> next;
            }
            return dummy -> next;
        }
    };
    View Code

    被链表支配的上午

  • 相关阅读:
    纪伯伦:我曾七次鄙视我的灵魂
    字典和集合
    元组
    列表
    字符串
    数值类型
    内置函数了解一下
    了解Python
    centos7安装mysql数据库
    xenserver 上传centos6.8镜像
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10043174.html
Copyright © 2011-2022 走看看