删除链表的倒数第N个节点

我的方法是用一个队列,保存后N个节点,但是内存消耗比较大,方法如下:

# 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:
        stackList = []
        
        from collections import deque
        stackList = deque(stackList)
        p = head
        while p is not None:
            if len(stackList) <= n:
                stackList.append(p)
            else:
                stackList.popleft()
                stackList.append(p)
            p = p.next
        
        if len(stackList) == n: #这里是为了应对出现stackList不满(即不是n+1)的情况
            stackList.popleft()
            try:
                return stackList[0]
            except:
                return None
        stackList[0].next = stackList[1].next
    
        return head

还用一种双指针方法:

# 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:
        headNode = ListNode(-1) #在head之前增加节点可以避免出现listNode长度和n一致的情况
        headNode.next = head
        front = headNode
        
        end = front
        
        for _ in range(n): #排头指针先跑n步,保证和队尾指针相差n,即队尾指针的next是要删除的
            front = front.next
            
        while front.next is not None:
            front = front.next
            end = end.next
        end.next = end.next.next
        
        return headNode.next

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章