Leetcode 19-21

No. 19 Remove Nth Node From End of List (重点)

Solution: 

The key point is how to navigate to the penultimate n nodes. The following way:

Start with the head (pre in code) to start the n + 1 nodes item (cur in code) before go to, like this pre with curm on the difference between n, and let the pre traverse until the cur cur been back to the last, then the pre .next is the penultimate n nodes.

code show as below:

 1 class Solution:
 2     def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
 3         pre = cur = head
 4         for _ in range(n):
 5             cur = cur.next
 6         if not cur:
 7             return head.next
 8         while cur.next:
 9             cur = cur.next
10             pre = pre.next
11         pre.next = pre.next.next
12         return head

No. 20 Valid Parentheses (EASY,PASS)


No. 21 Merge Two Sorted Lists (EASY,PASS)

 

Guess you like

Origin www.cnblogs.com/kedongh/p/10972797.html