双指针
# 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)
的方法。