(Python) algorithm dog dishes diary (list series) _leetcode 203. remove list elements

Delete the list is equal to a given value  val  all nodes.

Example:

Input: 1-> 2-> 6-> 3-> 4-> 5->. 6, Val =. 6
 Output: 1-> 2-> 3-> 4-> 5

This is the main problem is that the head node, given equal value, remove the head node

Method a: to remove the head node by adding a dummy head node

# 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:
        fakehead = ListNode(0)
        cur = fakehead
        fakehead.next = head
        while fakehead.next:
            if val == fakehead.next.val:
                fakehead.next = fakehead.next.next
            else:
                fakehead = fakehead.next
        return cur.next

Method 2: the value equal to a given wheel off the head node, the node is never equal to the value of the start process

# 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:
        if not head:
            return
        while val==head.val:
            head = head.next
            if not head:
                return head
        cur = head
        ccur = cur
        while(cur.next):
            if val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return ccur

 

 

Published 44 original articles · won praise 0 · Views 1907

Guess you like

Origin blog.csdn.net/weixin_39331401/article/details/104563173