【LeetCode 简单题】53-移除链表元素

声明:

今天是第53道题。删除链表中等于给定值 val 的所有节点。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

解法1。LeetCode上的最佳做法和这个思路差不多,耗时80 ms, 在Remove Linked List Elements的Python提交中击败了78.10% 的用户,代码如下。

# 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
        """
        dummy = ListNode(-1)
        dummy = head.next
        pre = dummy
        cur = head
        while cur:
            if cur.val == val:
                pre.next = cur.next    # 只要改变pre就可以删除元素了,改变的方式是跳过相等的元素,将next指向下下个元素
            else:
                pre = pre.next
            cur = cur.next    # 把这句放到if-else语句中耗时降为76ms,不知为啥
        return dummy.next    # 这个地方不能return head,提交会报超时

结尾

解法1:https://blog.csdn.net/guoziqing506/article/details/51273818

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83338787