时间:2020-6-3
题目地址:https://leetcode-cn.com/problems/remove-linked-list-elements/
题目难度:Easy
题目描述:
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
思路1:遍历链表节点,针对头节点写特殊逻辑
代码段1:通过
# 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 head == None:
return None
if head.next == None:
if head.val == val:
return None
else:
return head
while head != None and head.val == val:
start = head.next
head = head.next
if head != None and head.val != val:
start = head
while(head != None and head.next != None):
if head.next.val == val:
if head.next.next != None:
head.next = head.next.next
else:
head.next = None
else:
head.next = head.next
head = head.next
return start
总结:
- 我写的逻辑冗余且混乱,看下别人放的代码
# 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 head == None:
return None
# 头节点的特殊逻辑
while head != None and head.val == val:
head = head.next
start = head
# 处理节点
while(start != None and start.next != None):
if start.next.val == val:
start.next = start.next.next
else:
start = start.next
return head
思路2:遍历链表节点,针对头节点写特殊逻辑
官方的算法题解写的很清楚啊,我也需要多练习
代码段2:通过
# 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:
sentinel = ListNode(0)
sentinel.next = head
prev, curr = sentinel, head
while(curr):
if(curr.val == val):
prev.next = curr.next
else:
prev = curr
curr = curr.next
return sentinel.next
总结:
- 哨兵节点广泛应用于树和链表中,如伪头、伪尾、标记等,它们是纯功能的,通常不保存任何数据,其主要目的是使链表标准化,如使链表永不为空、永不无头、简化插入和删除。