leetcode61 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.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* rotateRight(ListNode* head, int k) {
12         ListNode *ans=NULL;
13         
14         int size=0;
15         ListNode *p=head;
16         while(p)
17         {
18             size++;
19             p=p->next;
20         }
21         if(size==0)
22             return ans;
23         
24         k=k%size;
25         
26         if(k==0)
27             return head;
28         
29         int t=size-k;
30         p=head;
31         while(--t)
32         {
33             p=p->next;
34         }
35         ListNode*pp=p->next;
36         p->next=NULL;
37         ans=pp;
38         while(pp->next!=NULL)
39         {
40             pp=pp->next;
41         }
42         pp->next=head;
43         return ans;
44         
45     }
46     
47 };
View Code

 

posted @ 2016-01-06 15:44  西小贝  阅读(151)  评论(0编辑  收藏  举报