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

    题目要求:

    删除链表中包含val的元素结点

    解题思路:

    重点在于找到第一个非val的头结点,然后遍历链表,依次删除值为val的结点,最后返回头结点

    方法:

    1、常规方法:

    找到第一个非val的头结点,如果头结点非NULL,遍历链表,依次删除值为val的结点,最后返回头结点。

    2、递归方法:

    代码:

    /**
     * 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) {
            while(head!=NULL && head->val==val)
                head=head->next;
            if(head==NULL)
                return head;
            // At least one node that does not contain val
            ListNode* cur;
            cur=head;
            while(cur->next!=NULL){
                if(cur->next->val==val)
                    cur->next=cur->next->next;
                else
                    cur=cur->next;
            }
            return head;
        }
    };
    /**
     * 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 && head->val==val) 
                head=removeElements(head->next,val);
            if(head && head->next) 
                head->next=removeElements(head->next,val);
            return head;
        }
    };
  • 相关阅读:
    Mercury产品介绍
    操纵txt文本文件
    MOSS开发辅助小工具
    Notes 8/8.5 超慢解决之道的最佳实践
    实战OO设计——OO设计原则
    SQL Server XML 拆分示例
    认识IL
    javascript 面向对象特性与编程实现
    MTV
    C#轻松仿造Vista风格窗体_cici 自娱自乐
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4461854.html
Copyright © 2011-2022 走看看