zoukankan      html  css  js  c++  java
  • Leecode刷题之旅-C语言/python-203移除链表元素

    /*
     * @lc app=leetcode.cn id=203 lang=c
     *
     * [203] 移除链表元素
     *
     * https://leetcode-cn.com/problems/remove-linked-list-elements/description/
     *
     * algorithms
     * Easy (39.58%)
     * Total Accepted:    18.3K
     * Total Submissions: 46.2K
     * Testcase Example:  '[1,2,6,3,4,5,6]
    6'
     *
     * 删除链表中等于给定值 val 的所有节点。
     * 
     * 示例:
     *       p  q
     * 输入: 1->2->6->3->4->5->6, val = 6
     * 输出: 1->2->3->4->5
     * 
     * 
     */
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* removeElements(struct ListNode* head, int val) {
        struct ListNode *p;
        if(head==NULL){
            return 0;
        }
        while(head!=NULL&&head->val==val)
            head = head->next;
    
        if(head==NULL)
            return 0;
    
        p = head;
        while(p->next!=NULL){
            if(p->next->val==val)
            p->next=p->next->next;
            else
            {
                p = p->next;
            }
        }
        return head;
    }

    思路非常简单,相同的删去断链就行。然后开头检查直到head不等于val。

    ------------------------------------------------------------------------------------------------

    python:

    #
    # @lc app=leetcode.cn id=203 lang=python3
    #
    # [203] 移除链表元素
    #
    # https://leetcode-cn.com/problems/remove-linked-list-elements/description/
    #
    # algorithms
    # Easy (39.58%)
    # Total Accepted:    18.3K
    # Total Submissions: 46.2K
    # Testcase Example:  '[1,2,6,3,4,5,6]
    6'
    #
    # 删除链表中等于给定值 val 的所有节点。
    # 
    # 示例:
    # 
    # 输入: 1->2->6->3->4->5->6, val = 6
    # 输出: 1->2->3->4->5
    # 
    # 
    #
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def removeElements(self, head: ListNode, val: int) -> ListNode:
            while head is not None and head.val == val:
                head = head.next
            current = head
            while current is not None:
                if current.next is not None and current.next.val == val:
                    current.next = current.next.next
                else:
                    current = current.next
            return head
  • 相关阅读:
    【学习总结】 小白CS成长之路
    Java程序员面试题收集(1)
    ECSTORE2.0 去页面底部版权
    vue-cli安装
    linux下安装nodejs
    Access denied for user 'root'@'localhost' (using password: YES)的解决
    想说的话
    十三:CSS之CSS的四种使用方法和优先级
    十二:CSS之基础语法
    十一:HTML之实现基本网页结构
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10550854.html
Copyright © 2011-2022 走看看