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;
        }
    };
  • 相关阅读:
    Python 重定向 响应头
    经典案例:如何优化Oracle使用DBlink的SQL语句
    django 文件上传
    mysite下的url 映射到news下的视图
    django 只允许POST或者GET
    云端的SRE发展与实践
    django 捕获url
    django 在自己app下编写自定义sql
    对偶学习及其在机器翻译中的应用
    对偶学习及其在机器翻译中的应用
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4461854.html
Copyright © 2011-2022 走看看