【LeetCode】打卡--Python3算法19. 删除链表的倒数第N个节点

版权声明:转载请说明出处,谢谢 https://blog.csdn.net/Asher117/article/details/89228737

【LeetCode】打卡–Python3算法19. 删除链表的倒数第N个节点

题目

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

结果–1.暴力法两层循环

执行用时 : 84 ms, 在Remove Nth Node From End of List的Python3提交中击败了21.13% 的用户
内存消耗 : 13.2 MB, 在Remove Nth Node From End of List的Python3提交中击败了33.09% 的用户

Python解答–1.暴力法两层循环

首先使用暴力法两次循环如下

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        N = 0
        left = head
        while(left):
            N = N + 1
            left = left.next
        if(N==1):
            return []
        if(N==n):
            return head.next
        right = head
        i = 1
        while(i < N-n):
            right = right.next
            i = i + 1
        right.next = right.next.next
        return head

结果–2.进阶版单层循环

执行用时 : 56 ms, 在Remove Nth Node From End of List的Python3提交中击败了76.84% 的用户
内存消耗 : 13.2 MB, 在Remove Nth Node From End of List的Python3提交中击败了36.83% 的用户

Python解答–2.进阶版单层循环

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        left = head
        right = head
        i = 0
        while(right.next):
            if(i < n):
                i = i + 1
            else:
                left = left.next
            right = right.next
            
        if(i == 0 or i < n):
            return head.next
        elif(n == 1):
            left.next = right.next
        else:
            left.next = left.next.next
        return head

我们下次再见,如果还有下次的话!!!
欢迎关注微信公众号:516数据工作室
516数据工作室

猜你喜欢

转载自blog.csdn.net/Asher117/article/details/89228737