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
.
終于又不看答案寫(xiě)出來(lái)一道m(xù)edium, 渣渣就是這么容易滿(mǎn)足。這道題一開(kāi)始也美看懂那個(gè)k指的是什么炸庞,后來(lái)用了幾個(gè)Custom Testcase自己看了下钱床,意思是從鏈表尾部往前數(shù)k個(gè)節(jié)點(diǎn)一起按原順序移動(dòng)到鏈表首部。
首先通過(guò)curt遍歷鏈表來(lái)計(jì)算節(jié)點(diǎn)總數(shù)total, 當(dāng)k > total的時(shí)候?qū)嶋H上移動(dòng)了k % total個(gè)元素埠居,所以干脆讓k = k % total. 同時(shí)prev被移動(dòng)到了原鏈表尾部查牌。根據(jù)題意,原鏈表尾部肯定會(huì)接上原鏈表首部滥壕,所以讓prev.next = head.
然后我們來(lái)找rotate后鏈表的頭纸颜。用prev來(lái)遍歷,count來(lái)計(jì)數(shù)绎橘,當(dāng)count == total - k的時(shí)候胁孙,prev.next就是新鏈表頭所在的位置。然后我們讓之前保存的dummy的next等于prev.next, 就設(shè)置好了新的鏈表頭,返回dummy.next即可浊洞。
/**
* 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;
}
}