您的位置:首页 > 其它

Leetcode 061 Rotate List

2016-05-08 11:59 274 查看
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.

思路:

1)遍历链表得到链表长度

2)找到要调整位置的链表结点的前一个结点

3)调整链表结构

注:当k>链表长度时,k=k%链表长度

具体代码如下:

/**
* 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 null;
}
if(k == 0){
return head;
}
int len = 0;
ListNode phead = new ListNode(0);
phead.next = head;
ListNode p = head;
int flag = 0;
ListNode end = null;
while(p!=null){
len++;
if(p.next == null){
end = p;
}
p = p.next;
}
if(k == len){
return head;
}
if(k>len){
k = k%len;
}
p = phead;
while(flag < len-k){
flag++;
p = p.next;
}
end.next = phead.next;
phead.next = p.next;
p.next = null;

return phead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表 LinkList