双指针
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
start = ListNode(0, head)
latehead = start
for i in range(n):
head = head.next
while head:
head = head.next
latehead = latehead.next
latehead.next = latehead.next.next
return start.next
栈
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
start = ListNode(0, head)
point=start
stack = list()
while point:
stack.append(point)
point = point.next
for i in range(n):
stack.pop()
stack[-1].next = stack[-1].next.next
return start.next
总结
1、双指针思路:后指针先移动n次,然后前后两指针一起移动,当后指针移动至末尾,则前指针在倒数第n个位置。
2、栈:将ListNode对象依次放入列表中,从后往前删除n次,则得到倒数第n+1个位置。
3、为了便于实现①找到倒数第n+1个对象;②返回值为第一个对象;③考虑返回值为空的情况。创建第一个对象时,采用start = ListNode(0, head)的方法。
这篇博客介绍了两种解决LeetCode第19题的方法,分别是双指针法和栈法。双指针法通过两个指针同步移动,找到倒数第N个节点并删除;栈法则利用栈保存节点,从后往前删除N个节点,找到目标位置。这两种方法都有效地解决了问题,并且在代码中进行了详细实现。

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



