Penultimate N nodes leetcode-19- delete the list

Subject description:

 

Method a: Pointer speed

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if not head:
            return
        dummy = ListNode(0)
        dummy.next = head
        fast = dummy
        while n:
            fast = fast.next
            n -= 1
        slow = dummy
        while fast and fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummy.next

 Method Two:

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        p_list = []
        p = head
        while p:
            p_list.append(p.val)
            p = p.next
        del p_list[-n]
        return p_list

 

Guess you like

Origin www.cnblogs.com/oldby/p/11161771.html