您的位置:首页 > 其它

leetcode 61. Rotate List

2017-07-05 13:24 423 查看
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-1个元素,将其next置空,再把后面的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(k==0||head==null||head.next==null)return head;
int count = 0;
ListNode p = head;
while(p!=null){
count++;
p = p.next;
}
if(k>count)k = k%count;
if(k==0)return head;
if(count==k){
return head;
}
p = head;
while(count!=k+1){
p = p.next;
count--;
}
ListNode a = p.next;
p.next = null;
ListNode b = a;
while(b.next!=null){
b = b.next;
}
b.next = head;
return a;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: