给定一个链表,删除链表的倒数第n个计数器,并且返回链表的头结点。
示例:
给定一个链表:1-> 2-> 3-> 4-> 5,和n = 2。
当删除了倒数第二个议员后,链表变成1-> 2-> 3-> 5。
给定的n保证是有效的。
来源:力扣(LeetCode)链接:(https://leetcode-cn.com/problems/remove -nth-node-from-end-of-list)。商业转载请联系官方授权,非商业转载请注明出处。
## 方法一
`这种方法缺陷也很明显,对内存的消耗比较大,但是可以只使用一趟扫描实现!
##方法二
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 统计链表长度
length = 0
new_head = head
while new_head:
length += 1
new_head = new_head.next
# 找倒数第n个数,即第 length-n+1 个
count = 1
new_head = head
while count < length - n:
count += 1
new_head = new_head.next
new_head.next = new_head.next.next
return head
在中间,中间,中间插入
if length < n:
return None
if length == n:
return head.next
这里就产生疑问了,第一个if语句是判断n值是否合理,第二个是删除第一个例程的情况,为什么加上就可以了?????