92. &206 Reverse Linked List II

题目要求:

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

For examples:

Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.

解题思路:寻找关键节点
  • 将head后移m-1个位置,找到逆置节点,记录其前驱节点和自己。


    步骤一
  • 从head节点开始逆置,逆置(m-n+1)个节点
  • 将所有节点相连


    步骤二、三
class ListNode():
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        # 有可能是从第一个节点开始逆序,所以pre指针并不能指向head,pre指针一般都是置为None

        pre = None
        m = m - 1
        length = n - m
        result = head

        # 将head放在逆序的开始位置
        while head and m:
            pre = head
            head = head.next
            m -= 1

        # 逆序的第一个节点将是逆序后的最后一个节点,需要保存为tail
        new_node = None
        next = None
        tail = head
        while head and length:
            next = head.next
            head.next = new_node
            new_node = head
            head = next
            length -= 1
        tail.next = head

        if pre:
            pre.next = new_node
        else:
            result = new_node

        return result

if __name__ == "__main__":
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    head.next.next.next = ListNode(4)
    head.next.next.next.next = ListNode(5)
    print(Solution().reverseBetween(head, 2, 4))

自己的新方法:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        diff, dummy, cur = n - m + 1, ListNode(-1), head
        dummy.next = head
        
        last_unswapped = dummy
        while head and m > 1:   #将cur放在逆序的开始位置,last_unsnapped
            cur, last_unswapped, m = cur.next, cur, m - 1
            
        prev = last_unswapped
        first_swapped = cur
        while cur and diff > 0:
            prev.next, cur.next, cur, diff = cur, prev.next, cur.next, diff - 1   #新学的方法,哈哈哈哈哈哈哈
        
        last_unswapped, first_swapped.next = prev, cur    #last_unswapped不要赋值
        
        return dummy.next

你可能感兴趣的:(92. &206 Reverse Linked List II)