19. 删除链表的倒数第 N 个结点 @Python @Go

原题

https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/

思路

虚拟节点

复杂度

时间:O(n)
空间:O(1)

Python代码

# 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: Optional[ListNode], n: int) -> Optional[ListNode]:
        def getLength(head):
            ans = 0 
            while head:
                ans += 1 
                head = head.next
            return ans 
        
        dummy = ListNode(0, head)
        cur = dummy
        length = getLength(head)
        for i in range(length - n):
            cur = cur.next 
        cur.next = cur.next.next 
        return dummy.next

        

Go代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

func getLength(head *ListNode) int {
	ans := 0
	for head != nil {
		ans++
		head = head.Next
	}
	return ans
}

func removeNthFromEnd(head *ListNode, n int) *ListNode {
	// 虚拟节点指针
	dummy := &ListNode{Next: head}
	cur := dummy
	length := getLength(head)
	for i := 0; i < length-n; i++ {
		cur = cur.Next
	}
	cur.Next = cur.Next.Next
	return dummy.Next
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值