leetcode Featured Training 61. Rotate List

The problem with this method is slightly different explanations Official, Official Interpretations list is again traversed to obtain the length of the list, the list and then point to the end of list head to form a ring, the linked list to find a suitable location is disconnected. My method is to use the double pointer, resulting in the length of the list, while another pointer p2 point to the appropriate position (if k <chain length), if k> chain length, then the need to get the length of the list, then the other pointer p2 point to the appropriate position. After the pointer to the right position p2, the rotating operation can be performed. See specific rotational operation code.
(Place: the results of a former head of the list in the list of the original)

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

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        # 特殊情况处理
        if k == 0:
            return head
        if head == None:
            return head

        # 重新添加链表头
        hea = ListNode(0)
        hea.next = head

        # 计算链表长度,同时将p1移动到链表最后一个元素,利用双指针,将p2移动到合适位置(结果链表头的前一位)
        l = 0 # 链表长度
        p1 = hea
        p2 = hea
        while p1.next != None:
            p1 = p1.next
            l += 1
            if l > k: # 双指针
                p2 = p2.next

        # 如果l<=k则p1到达末尾时p2还在原始链表头,所以此时要特殊处理,使p2到达合适位置
        if l <= k:
            k = k%l
            if k == 0:
                return head
            for i in range(l-k):
                p2 = p2.next
            
        # 旋转操作
        tmp = p2.next
        p2.next = None
        p1.next = hea.next
        hea.next = tmp
        return hea.next
Published 201 original articles · won praise 26 · views 80000 +

Guess you like

Origin blog.csdn.net/Ema1997/article/details/104078006