Rotate List

此题没有其他办法,一开始必须先统计一遍链表的长度,如果k大于长度则去模再求解,主逻辑需要快慢指针来进行链表的旋转

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

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if k == 0:
            return head

        if not head:
            return None

        count = 0
        cur = head
        while cur:
            cur = cur.next
            count += 1
        k %= count

        root, tail = head, head
        while k > 0:
            tail = tail.next
            k -= 1

        while tail.next:
            root = root.next
            tail = tail.next

        tail.next = head
        result = root.next
        root.next = None
        return result

results matching ""

    No results matching ""