面试题27:单链表向右旋转k个节点

Given a list, rotate the list to the right by kplaces, where k is non-negative.

For example:
Given1->2->3->4->5->NULLand k =2,
return4->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         if(head == nullptr || head->next == nullptr) return head;
13 
14         int length = 0;
15         ListNode* p = head;
16         while(p){
17             length++;
18             p = p->next;
19         }
20         k = k % length;
21         if(k == 0) return head;
22         int m = length - k;
23         p = head;
24         while(m > 1){
25             p = p->next;
26             m--;
27         }
28         ListNode* right = p->next;
29         p->next = nullptr;
30         p = right;
31         while(p->next){
32             p = p->next;
33         }
34         p->next = head;
35         head = right;
36         return head;
37     }
38 };

 

posted @ 2017-05-19 10:47  wxquare  阅读(298)  评论(0编辑  收藏  举报