Leetcode 92. Reverse Linked List II
阿新 • • 發佈:2020-11-20
Description: Reverse a linked list from position m to n. Do it in one-pass. Note:1 ≤ m ≤ n ≤ length of list.
Link: https://leetcode.com/problems/reverse-linked-list-ii/
Examples:
Example: Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverseBetween(self, head, m, n):""" :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if not head: return head if not head.next: return head if m == n: return head if m == 1: p = head q = p.next p.next= None length = 1 while q: f = q.next q.next = p p = q q = f length += 1 if length == n: break head.next = q return p else: pre = head p = head.next length = 2 # p is the second node, so length start by 2 while p: if length == m: rvs_head = p # rvs_head is m Node before reverse, afterwards be n Node end = pre # end is the m-1 Node break pre = p p = p.next length += 1 q = p.next length += 1 # now q is the moving node, and q=p.next make length plus 1 p.next = None while q and length <= n: f = q.next q.next = p p = q q = f length += 1 end.next = p # p is the head of reversed linked list rvs_head.next = q # q is the head of list begin by n+1 Node return head
顯然,這個程式碼太長了,有明顯的冗餘,癥結在於m-1不合法,那不妨在head前加root節點,即使m=1,m-1可以指向root. 但是下面這個程式碼,時間和空間都佔用更多。
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if not head: return head if not head.next: return head if m == n: return head root = ListNode(0) root.next = head pre = root p = root.next length = 1 while p: if length == m: rvs_head = p end = pre break pre = p p = p.next length += 1 q = p.next length += 1 p.next = None while q and length <= n: f = q.next q.next = p p = q q = f length += 1 end.next = p rvs_head.next = q return root.next
日期: 2020-11-20 今天很充實,很開心