【LeetCode】19. Remove Nth Node From End of List

我的个人微信公众号:Microstrong

微信公众号ID:MicrostrongAI

微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!

知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

个人博客:https://blog.csdn.net/program_developer

19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

解题思路:

(1)两遍扫描法

第一遍扫描获取长度,第二遍扫描找到被删除节点的前驱节点,然后删除节点。

已经AC的代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head is None:
            return head

        count = 0
        tempHead = head
        while tempHead:
            count += 1
            tempHead = tempHead.next

        if count == 1:
            return None

        node = head
        temp = 0
        while node:
            temp += 1
            if count - n == 0:
                head = head.next
                return head
            if temp == (count - n):
                removeNode = node.next
                lastNode = removeNode.next
                node.next = lastNode
                break
            node = node.next
        return head

(2)前后指针法

通过两个指针,让第一个指针出发n步后,第二个指针继续出发。当第一个指针到达尾部后,第二个指针刚好能够到达被删除节点。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if not head:
            return head

        if n == 1 and head.next == None:
            return head.next

        fast = head
        slow = head
        while n:
            fast = fast.next
            n -= 1
        if not fast:
            return head.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        node = slow.next.next
        slow.next = node

        return head

Reference

【1】19. 删除链表的倒数第N个节点,地址:https://zhuanlan.zhihu.com/p/105905356?utm_source=wechat_session&utm_medium=social&utm_oi=743812915018104832  

你可能感兴趣的:(LeetCode)