fix:移除链表元素

上级 ad7247dd
"""
移除链表元素
"""
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
"""
链表的合适是操作2个节点,前驱和后继
:param head:
:param val:
:return:
"""
# 处理头部节点
while head and head.val == val:
head = head.next
# 处理非头部
cur = head
while cur and cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head
if __name__ == '__main__':
# 1, 2, 6, 3, 4, 5, 6
l1 = ListNode(7)
l1.next = ListNode(7)
l1.next.next = ListNode(7)
l1.next.next.next = ListNode(7)
# l1.next.next.next.next = ListNode(7)
# l1.next.next.next.next.next = ListNode(7)
# l1.next.next.next.next.next.next = ListNode(7)
# l2 = ListNode(5)
# l2.next = ListNode(6)
# l2.next.next = ListNode(1)
# l2.next.next.next = ListNode(8)
# l2.next.next.next.next = ListNode(4)
# l2.next.next.next.next.next = ListNode(5)
result = Solution().removeElements(l1, 7)
print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册