[LinkList]92. Reverse Linked List II

  • 分類:LinkList
  • 時間復雜度: O(n)
  • 空間復雜度: O(n)

92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ mn ≤ length of list.

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:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseBetween(self, head: 'ListNode', m: 'int', n: 'int') -> 'ListNode':
        
        res=ListNode(0)
        p=res
        
        #第一遍for循環(huán)找到m-1的位置,m的位置,n的位置
        current=head
        for i in range(n):
            if i<=m-2:
                p.next=current
                p=p.next
            if i==m-1:
                mNode=current
            if i==n-1:
                nNode=current
            current=current.next
        
        #每次都使prev的next=current,然后current等于當前的prev
        while n-m>0:
            prev=ListNode(mNode.val)
            prev.next=current
            mNode=mNode.next
            current=prev
            m+=1
        mNode.next=current
        p.next=mNode
            
        
        return res.next

討論:

1.鏈表題好他媽的眩暈...
2.這是206的一道follow up,這兩個題的解法如下:


21881550245660_.pic_hd.jpg
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容