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.
Have you been asked this question in an interview?
这题之所以通过率不高是因为大家不知道怎么理解题意,其实就是反转k%n步就行了
这题之所以通过率不高是因为大家不知道怎么理解题意,其实就是反转k%n步就行了
- ListNode *rotateRight(ListNode *head, int k) {
- if(head==NULL)
- return NULL;
- int length=0;
- for(ListNode *p=head;p!=NULL;p=p->next)
- length++;
- k=k%length;
- if(k==0)
- return head;
- ListNode *p0=head;
- ListNode *p1=head;
- int i=0;
- for(;i<k && p1!=NULL;i++){
- p1=p1->next;
- }
- while(p1->next!=NULL){
- p0=p0->next;
- p1=p1->next;
- }
- ListNode *tmp=p0->next;
- p1->next=head;
- p0->next=NULL;
- return tmp;
- }
相关热门文章
给主人留下些什么吧!~~
评论热议