leetcode--Rotate List
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;
}
};
浙公网安备 33010602011771号