题目如下:
题目
这道题说明了给定的删除位置肯定是可行的,所以就不用对n进行判断。这道题提供两种解法,第一种,利用python的 list 来把删除节点,参考答案如下:
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
node_list = []
while head:
node_list.append(head)
if head.next is None:
break
else:
head = head.next
if len(node_list) == 1:
return None
elif len(node_list) == n:
node_list.pop(0)
return node_list[0]
n = 0 - n
node_list[n - 1].next = node_list[n].next
node_list.pop(n)
return node_list[0]
第二种采用双指针的方法,其思想是通过第二个指针将删除节点找出来,然后处理节点链接,参考代码如下:
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
head0 = ListNode(0)
head0.next = head
runner = head0
walker = head0
for i in range(n):
runner = runner.next
while runner.next:
walker = walker.next
runner = runner.next
node = walker.next
walker.next = node.next
node.next = None
return head0.next
ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客:tundrazone.com
网友评论