垃圾小白羊的leetcode刷题记录7

垃圾小白羊的leetcode刷题记录7_第1张图片
我的解法:

class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        count = 0
        dummy = ListNode()
        dummy.next = head
        p = dummy
        inv_nodes = []
        while count <= n:
            if count == m-1:
                first_pre = p
            if m <= count <= n:
                inv_nodes.append(p)
            p = p.next
            count += 1
        
        for i in range(len(inv_nodes)-1,0,-1):
            inv_nodes[i].next = inv_nodes[i-1]

        first_pre.next = inv_nodes[-1]
        inv_nodes[0].next = p
        return dummy.next

定义一个伪头节点,从伪头节点开始遍历一遍链表,遍历过程中计数,遍历到第m-1个节点时,用指针first_pre记录指向节点,将第m到第n个节点储存到列表中。遍历到第n+1个节点时,停止遍历,此时p指向第n+1个节点。将列表中的节点从后往前反向链接,在将first_pre指向列表最后一个节点,即将原链表头部接上翻转后的链表,而列表第一个节点指向指针p即接上剩余原链表。时间复杂度最坏情况为O(n),空间复杂度O(n)。

大佬解法:

class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        count = 1
        dummy = ListNode()
        dummy.next = head
        pre, cur = dummy, head
        while count <= n:
            if count == m:
                fp = pre
            if m+1<=count<=n:
                third = cur.next
                cur.next = pre
                pre = cur
                cur = third
            else:
                cur = cur.next
                pre = pre.next
            count += 1
        fp.next.next = cur
        fp.next = pre
        return dummy.next

利用三个指针可以实现一次遍历修改链表方向O(n),空间复杂度O(1)。

你可能感兴趣的:(小白羊不太会编程,数据结构,leetcode)