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

posted @ 2019-03-26 09:12  banananana  阅读(196)  评论(0编辑  收藏  举报