Python教程

0019-leetcode算法实现之删除链表倒数第n个节点-remove-nth-node-from-end-of-list-python&golang实现

本文主要是介绍0019-leetcode算法实现之删除链表倒数第n个节点-remove-nth-node-from-end-of-list-python&golang实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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

示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:

输入:head = [1], n = 1
输出:[]
示例 3:

输入:head = [1,2], n = 1
输出:[1]

提示:

链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

python

# 0019.删除倒数第N个节点
# 参考:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/dong-hua-tu-jie-leetcode-di-19-hao-wen-ti-shan-chu/
class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None

class Solution:
    def removeNthFromENd(self, head: ListNode, n: int) -> ListNode:
        """
        双指针,一趟遍历,时间O(n), 空间O(1)
        思路:
        - 假设链表长度L(未知), 设置虚拟节点,指向head, 初始化p1,p2指针,从虚拟节点开始
        - 固定p1,移动p2指针n+1步
        - 同时移动p1,p2,直到p2指针到末尾,
        - 此时p2指针又走了L-n-1步, 同理p1指针也走了L-n-1步,p1指针的下个节点即为删除节点,删除即可
        - 最后返回head节点
        :param head:
        :param n:
        :return:
        """
        dummyHead = ListNode(0)
        dummyHead.next = head
        p1, p2 = dummyHead, dummyHead
        for i in range(0, n+1):
            p2 = p2.next
        while p2:
            p1 = p1.next
            p2 = p2.next

        p1.next = p1.next.next
        retNode = dummyHead.next
        dummyHead.next = None
        return retNode

golang

// 双指针
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	dummyHead := &ListNode{}
	dummyHead.Next = head
	p1, p2 := dummyHead, dummyHead

	for i := 0; i < n+1; i++ {
		p2 = p2.Next
	}
	for p2 != nil {
		p1 = p1.Next
		p2 = p2.Next
	}
	p1.Next = p1.Next.Next
	retNode := dummyHead.Next
	dummyHead.Next = nil
	return retNode
}

这篇关于0019-leetcode算法实现之删除链表倒数第n个节点-remove-nth-node-from-end-of-list-python&golang实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!