leetcode61~Rotate List

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.

對鏈表從右側k個數進行翻轉。
注意:k可以大於鏈表的長度,需要對鏈表長度取餘

public class RotateList {
public ListNode rotateRight(ListNode head, int k) {
if(head==null || k<1) return head;
int count = 1;
ListNode cur = head;
while(cur.next!=null) {
cur = cur.next;
count++;
}
//此時cur指向最後一個節點
ListNode tail = cur;
//k可以大於鏈表長度
k = k%count;
if(k==0) return head;
int tmp = count - k;
//cur重新指向頭節點
cur = head;
while((–tmp)!=0) {
cur =cur.next;
}
//此時cur指向要翻轉節點的前一個節點
tail.next = head;
//對head重新賦值
head = cur.next;
cur.next = null;
return head;
}
}

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