数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录
1. 题目
leetcode 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/comments/
2. 解答
使用双指针p1,p2 ,p1先走n 步长,然后p1,p2同时开始,p1为空的时候结束
python:28 ms,10.9 MB
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first_p = second_p = head
cnt = 0
while first_p != None:
if cnt <= n:
first_p = first_p.next
cnt += 1
continue
first_p = first_p.next
second_p = second_p.next
cnt += 1
if cnt == 1:
return None
elif cnt == n:
return head.next
else:
second_p.next = second_p.next.next
return head
其他方法看 leetcode 链接 评论区~