19. 删除链表的倒数第 N 个结点

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

 

示例 1:


输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:

输入:head = [1], n = 1
输出:[]
示例 3:

输入:head = [1,2], n = 1
输出:[1]
 

提示:

链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

方法1(两次扫描)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        # 两趟扫描
        l = []
        while head:
            l.append(head.val)
            head = head.next
        
        new_head = ListNode(0)
        p = new_head

        for i in range(len(l)):
            if i == len(l) - n:
                continue

            p.next = ListNode(l[i])
            p = p.next
            
        return new_head.next
        

 

方法2(两次扫描)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        # 两趟扫描
        l = self.getLength(head)
        dummy = ListNode(0, head)
        p = dummy
        
        i = 0
        while p:
            if i == l - n:
                p.next = p.next.next # 删除节点
                break
            i += 1
            p = p.next
        
        return dummy.next
    
    def getLength(self, p):
        l = 0
        while p:
            l += 1
            p = p.next
        return l

 

posted @ 2021-11-02 22:02  风不再来  阅读(26)  评论(0编辑  收藏  举报