19. Remove Nth Node From End of List(移除倒数第N的结点, 快慢指针)

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

 

# 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 | None, n: int) -> ListNode | None:
        cnt = 0
        cur = head
        while cur:
            cur = cur.next
            cnt+=1
        step = cnt - n
        fake = ListNode()
        fake.next = head
        cur = fake
        for _ in range(step):
            cur = cur.next
        
        n = cur.next
        cur.next =n.next
        n.next = None
        return fake.next

 

 

思路:

利用快指针先走n步,找到倒数第n个节点

然后删除。

 

# 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: Optional[ListNode], n: int) -> Optional[ListNode]:
        fake = ListNode(-1,head)
        pre = fake
        fast = head
        for i in range(n):
            fast = fast.next
        slow = head
        while fast:
            slow = slow.next
            fast = fast.next
            pre = pre.next
        pre.next = slow.next
        slow.next = None
        return fake.next
     


posted @ 2017-10-23 20:19  乐乐章  阅读(179)  评论(0)    收藏  举报