您的位置:首页 > 其它

leetcode--Rotate List

2014-11-12 14:01 155 查看
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
.

为了方便,使用了哨兵节点。

java:

/**
* 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) {
if(head==null||head.next==null||n==0)
return head;
int cnt=0;
ListNode p=head;
while(p!=null){
cnt++;
p=p.next;
}
if(n==cnt)
return head;
n=n%cnt;
if(0==n)
return head;
ListNode h = new ListNode(-1);
h.next=head;
ListNode q=h;
int step=0;
while(step<n){
step++;
q=q.next;
}
p=h;
while(q.next!=null){
q=q.next;
p=p.next;
}
q.next=h.next;
h.next=p.next;
p.next=null;

return h.next;

}
}


c++:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(!head||!head->next||0==k){
return head;
}
ListNode *p=head;
int N=0;
while(p){
N++;
p=p->next;
}
if(k==N)
return head;
k=k%N;
if(k==0)
return head;
ListNode *h = (ListNode *)malloc(sizeof(ListNode));
h->next=head;

ListNode*q=h;
int cnt=0;
while(cnt<k){
cnt++;
q=q->next;
}
p=h;
while(q->next){
q=q->next;
p=p->next;
}
q->next=h->next;
h->next=p->next;
p->next=NULL;

ListNode *s =h->next;
free(h);
return s;

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