March-61. Rotating Linked List

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next or not k: return head
        tmp, count= head, 0
        #先计算链表总长度
        while tmp:
            tmp = tmp.next
            count += 1
        #取余
        k = k % count

        #如果k=0不用反转
        if k == 0:
            return head
        
        #设置快慢指针,让快指针比慢指针快走k步
        fast = slow = head
        for i in range(k):
            fast = fast.next
        
        #然后快慢指针起步走,这样就能保证找到倒数的k个节点
        while fast.next:
            fast = fast.next
            slow = slow.next
        
        #断掉链表
        newHead = ListNode(0)
        newHead = slow.next
        
        #让原链表的下个节点为None
        slow.next = None
        #让快指针指向head即可
        fast.next = head
        return newHead
  • The basic idea
    • First calculate the total length of the linked list, and then k takes the remainder of the total length
    • If the result of taking in is 0, put it back directly
    • Otherwise, set the fast and slow pointer, let the fast pointer go k steps first
    • Then the fast and slow pointers move synchronously until the fast pointer reaches the end of the linked list
    • Set a new node newHead, which is equal to the next node of the slow pointer
    • Then let the next node of the slow pointer be empty, disconnect the linked list, and let the next pointer of the fast pointer point to the head node of the linked list
    • Then return to the new node, this is the new linked list after flipping 

In fact, the essence is to flip the k elements, and then exchange the order with the previous linked list . This picture by fuxuemingzhu is good. fuxuemingzhu

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/115262379