# 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]:
# 思路是先统计总个数,然后循环找到节点前一个,更改next
count=0
copy_head=head
ans_head=head
while head:
count=count+1
head=head.next
if count==n:
return ans_head.next
for i in range(count-n-1):
copy_head=copy_head.next
copy_head.next=copy_head.next.next if copy_head.next.next else None
return ans_head
思路是:
- 首先统计一下整个链表长多少
- 然后使用for循环到要删除的前一个节点,next操作
- 同时这里要注意踢出一个条件,就是当要删除第一个节点时,直接返回第二个节点。
双指针解法
思路:
- pre节点指向head的前一个节点
- slow 赋值为pre,fast 赋值为head
- 先让fast走n步
- 然后,fast slow 一起走,直到while fast,这时候slow 到要删除的节点的前一个节点
- 然后next操作
# 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]:
#10:45
'''
Two pointer
'''
#this is needed bcuz what if first Node need to be removed
dummyHead = ListNode(0, head)
slow, fast = dummyHead, head
i = 0
while i != n:
i += 1
fast = fast.next
while fast != None:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummyHead.next