您的位置:首页 > 其它

LeetCode 92 Rotate List

2014-10-27 13:45 477 查看
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有可能超过链表长度,因此要有个取余操作。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
//这里有个问题,就是k有可能大于链表长度
if(head == null || head.next == null)
return head;
ListNode point = head;
int len = 1;
while(point.next != null){
point = point.next;
len++;
}
point.next = head;//连成环
int count = len - n%len;
while(count > 0){
point = point.next;
count--;
}
head = point.next;//断开环
point.next = null;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息