zoukankan      html  css  js  c++  java
  • 203. 移除链表元素

    203. 移除链表元素

    题意

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

    解题思路

    1. 把下个结点的值赋值给当前结点,删除下一个结点;

    2. 增加一个多余的头结点,方便记录下前结点,将前结点指向下个结点,删除当前结点;

    实现

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None

    class Solution(object):
       def removeElements(self, head, val):
           """
          :type head: ListNode
          :type val: int
          :rtype: ListNode
          """
           node = head
           while node and node.val != val:
               node = node.next
           
           while node:
               if node.val == val:
                # 把下个结点的值赋值给当前结点,实际是删除下一个结点
                   if node.next != None:
                       node.val = node.next.val
                       node.next = node.next.next
                   elif head == node:  # 头结点
                       head = None
                       break
                   else: # 尾结点
                       cur = head
                       while cur.next and cur.next != node:
                           cur = cur.next
                       cur.next = None
                       break
               else:
                   node = node.next
           return head
         
    def removeElements(self, head, val):
           """
          :type head: ListNode
          :type val: int
          :rtype: ListNode
          """
           # 新增一个起始结点,方便获取前结点(比如在删除首结点的时候)
           start = ListNode(0)
           start.next = head
           prev = start
           cur = head
           
           while cur is not None:
               if cur.val != val:
                   prev = cur
                   cur = cur.next
               else:
                   prev.next = cur.next
                   cur = prev.next
                   
           return start.next
         
       def removeElements(self, head, val):
           """
          :type head: ListNode
          :type val: int
          :rtype: ListNode
          """
           try:
               while head.val == val:
                   head = head.next
               cur = head
               nex = cur.next
               while nex:
                   if nex.val != val:
                       cur.next = nex
                       cur = cur.next
                   nex = nex.next
               if cur.next.val == val:
                   cur.next = None
           except:
               True
           return head

  • 相关阅读:
    Docker容器监控
    Docker Compose集成式应用组合及service编排
    Docker数据挂载
    Docker 构建私有仓库
    Dockerfile构建私有镜像
    Docker常用命令
    【手记】Reflexil直接让方法返回true或false
    【组件分享】自定义窗口标题菜单
    DLL/OCX文件的注册与数据执行保护DEP
    【SQL】用SSMS连接Oracle手记
  • 原文地址:https://www.cnblogs.com/George1994/p/10598117.html
Copyright © 2011-2022 走看看