leetcode 203 Remove Linked List Elements 移除链表元素 python

版权声明:作者:onlychristmas 欢迎转载,与人分享是进步的源泉! 转载请保留原博客地址:https://blog.csdn.net/huhehaotechangsha https://blog.csdn.net/huhehaotechangsha/article/details/88681980
所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。
'''

Remove all elements from a linked list of integers that have value val.

Example:

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


'''

# 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:

        # Approach one
        last = ListNode(0)
        last.next = first = head
        while first:
            if first.val == val:
                last.next = last.next.next
                if first == head: head = head.next    # 删除头结点特殊处理
            else:
                last = first
            first = first.next
        return head



所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。

猜你喜欢

转载自blog.csdn.net/huhehaotechangsha/article/details/88681980
今日推荐