【leetcode每日刷題】61. Rotate List

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

 

import java.util.List;

class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }
 
public class num61 {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null) return head;
        int len = 0;
        ListNode p = head;
        while(p != null){
            len += 1;
            p = p.next;
        }
        if(k%len == 0) return head;
        int count = len - k%len;
        p = head;
        while(count-1 > 0){
            count -= 1;
            p = p.next;
        }
        ListNode right = p.next;
        ListNode s = right;
        p.next = null;
        while(right.next!=null){
            right = right.next;
        }
        right.next = head;
        return s;
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        int k = 2;
        ListNode p = head;
        for(int i=2; i<6; i++){
            p.next = new ListNode(i);
            p = p.next;
        }
        num61 solution = new num61();
        ListNode result = solution.rotateRight(head, k);
        while(result!=null){
            System.out.println(result.val);
            result = result.next;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章