原题
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
}

被折叠的 条评论
为什么被折叠?



