黄哥Python, Remove Nth Node From End of List 代码

202 阅读1分钟
原文链接: zhuanlan.zhihu.com

这个题目的意思是删除从尾部起第N个节点。

Loading...leetcode.com图标

Given a linked list, remove then-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.

这个题目的解题技巧,设置二个快慢指针,让快指针先走N步后,慢指针和快指针同时往后移动,当快指针移动到尾部后,这个时候慢指针的下一个节点就是要被删除的节点。

请看Python 代码 和Go 代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
// 黄哥Python培训 黄哥所写
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head is None:
            return None
        fast, slow = head, head
        for _ in range(n):
            fast = fast.next
        if fast is None:
            head = head.next
            return head
        
        while fast.next != None:
            fast = fast.next
            slow = slow.next
        
        slow.next = slow.next.next
        return head

下面是Go 语言代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
    var fast, slow *ListNode
    fast = head
    slow = head
    for i := 0; i < n; i++ {
        fast=fast.Next
    }
    if fast == nil {
        head = head.Next
        return head
    }
    for fast.Next != nil {
        fast = fast.Next
        slow =  slow.Next
    }
    slow.Next = slow.Next.Next
    return head
}
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标