zoukankan      html  css  js  c++  java
  • LintCode Python 简单级题目 452.删除链表中的元素

    原题描述:

    删除链表中等于给定值val的所有节点。

    样例

    给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5

    题目分析:

    删除链表中等于给定值val的所有节点。

    遍历链表,找到其中next.val等于val的节点,删除。

    注意的地方就是可能链表中的所有元素val都等于val,循环的开始需要从表头开始删除,需要新增一个头节点。

     

    源码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @param val, an integer
        # @return a ListNode
        def removeElements(self, head, val):
            # Write your code here
            if head is None:
                return None
            # 可能链表中的所有元素val都等于val,所以需要新增一个头节点
            new = ListNode(0)
            new.next = head
            head = new
            pre = head
            # 遍历链表,删除等于val的所有节点
            while pre.next is not None:
                if pre.next.val == val:
                    pre.next = pre.next.next
                else:
                    pre = pre.next
            return new.next
  • 相关阅读:
    caffe:使用C++来提取任意一张图片的特征(从内存读取数据)
    python:控制鼠标和键盘
    .dll 文件编写和使用
    python:打包成exe程序
    python:小乌龟turtle
    python:input()和raw_input()
    C++:哈希
    C++:线程(std::thread)
    GitHub:Git的使用
    链表
  • 原文地址:https://www.cnblogs.com/bozhou/p/6956043.html
Copyright © 2011-2022 走看看