您的位置:首页 > 其它

61. Rotate List

2016-01-13 17:33 197 查看
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.

双指针法

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null) return head;
ListNode p = head,q = head;
int size = 1;
while (p.next != null) {    //单链表长度
p = p.next;
size++;
}
p = head;
k = k%size;
if(k == 0) return head;
for (int i = 0; i < k; i++) {
q = q.next;
}
while(q.next != null){
p = p.next;
q = q.next;
}
ListNode newhead = p.next;
p.next = null;
q.next = head;
return newhead;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: