61. Rotate List

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

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

终于又不看答案写出来一道medium, 渣渣就是这么容易满足。这道题一开始也美看懂那个k指的是什么,后来用了几个Custom Testcase自己看了下,意思是从链表尾部往前数k个节点一起按原顺序移动到链表首部。
首先通过curt遍历链表来计算节点总数total, 当k > total的时候实际上移动了k % total个元素,所以干脆让k = k % total. 同时prev被移动到了原链表尾部。根据题意,原链表尾部肯定会接上原链表首部,所以让prev.next = head.
然后我们来找rotate后链表的头。用prev来遍历,count来计数,当count == total - k的时候,prev.next就是新链表头所在的位置。然后我们让之前保存的dummy的next等于prev.next, 就设置好了新的链表头,返回dummy.next即可。

61. Rotate List_第1张图片
WechatIMG53.jpeg
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0){
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode curt = head;
        int total = 0;
        while (curt != null){
            total++;
            curt = curt.next;
            prev = prev.next;
        }
        k = k % total;
        prev.next = head;
        int count = 0;
        while (count < total - k){
            prev = prev.next;
            count++;
        }
        dummy.next = prev.next;
        prev.next = null;
        return dummy.next; 
    }
}

你可能感兴趣的:(61. Rotate List)