您的位置:首页 > 其它

LintCode:旋转链表

2015-11-24 23:03 260 查看
给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
您在真实的面试中是否遇到过这个题?

Yes

样例

给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null

标签 Expand

相关题目 Expand

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if(head == null ) return null;
ListNode c = head;
int count = 0;
while(c!=null){
count++;
c = c.next;
}
ListNode x = head;
ListNode res = new ListNode(-1);
ListNode  y  =   res;
ListNode front = new ListNode(-1);
ListNode  z  =   front;
for(int i=0;i<count-k%count&&x!=null;i++){
z.next = x;
z = z.next;
x = x.next;
}
z.next = null;
while(x!=null){
y.next = x;
y = y.next;
x = x.next;
}
y.next = front.next;
return res.next;
}
}



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