Programming

Leetcode-61. Rotate List

Leetcode-61. Rotate List

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4
Output: [2,0,1]

<解題>

  1. 判斷若為空,直接返回head
  2. 建立一個dummy ListNode,並將他指向head
  3. 建立fast, slow ListNode,等於dummy(從頭)
  4. 用fast指標來算出總長度
  5. 用slow指標找到要旋轉的位置
  6. 進行旋轉操作

image


class Solution {
    public ListNode rotateRight(ListNode head, int k) {
    if(head == null||head.next==null) return head;

    ListNode index = head;
    int len = 1; //計算長度
    while(index.next != null){
        index = index.next;
        len++;
    }

    index.next = head;
    for(int i =1; i< len - k % len;i++){
        head = head.next;
    }
    ListNode res = head.next;
    head.next = null;

    return res;
}
}

Time Complexity: O(n) Space Complexity: O(1)

自己測試的資料


public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();

        // Create a linked list from the array
        ListNode head = createLinkedList(new int[]{1, 2, 3, 4, 5,6});

        // Rotate the linked list
        int n = 2;
        ListNode rotatedHead = solution.rotateRight(head, n);

        // Print the resulting linked list
        printLinkedList(rotatedHead);
    }

    // Helper method to create a linked list from an array
    private static ListNode createLinkedList(int[] nums) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        for (int num : nums) {
            current.next = new ListNode(num);
            current = current.next;
        }
        return dummy.next;
    }

    // Helper method to print the elements of a linked list
    private static void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }
}