1.第一题:
这一道题用双指针,second指针向first指针后移n-1位,当second指针移到表尾时,first指针表示需要删除的节点,使用指针a表示first指针的前一节点。要考虑当删除的是头节点时的特殊情况、还有只有一个节点和两个节点的情况。代码如下:
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
first=head
a=head
second=head
if head.next==None:
return None
elif head.next.next==None:
if n==1:
head.next=None
return head
if n==2:
return head.next
while n!=1:
second=second.next
n-=1
while second.next!=None:
a=first
first=first.next
second=second.next
if first==head:
head=head.next
else:
a.next=first.next
return head
2.第二题:
代码如下:
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return
stack=[root]
prev=None
while stack:
curr=stack.pop()
if prev:
prev.left=None
prev.right=curr
left,right=curr.left,curr.right
if right:
stack.append(right)
if left:
stack.append(left)
prev=curr