标签:style blog http io ar color os sp for
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
.
Linked List Two Pointers
1 #include <iostream> 2 using namespace std; 3 4 /** 5 * Definition for singly-linked list. 6 */ 7 struct ListNode { 8 int val; 9 ListNode *next; 10 ListNode(int x) : val(x), next(NULL) {} 11 }; 12 13 class Solution { 14 public: 15 ListNode *rotateRight(ListNode *head, int k) { 16 if(head==NULL||k==0) return head; 17 int cnt =0; 18 ListNode * first=head,*slow=head; 19 while(cnt<k){ 20 if(first==NULL) first = head; 21 first=first->next; 22 cnt++; 23 } 24 if(first==NULL) return head; 25 while(first->next!=NULL){ 26 first=first->next; 27 slow=slow->next; 28 } 29 first->next=head; 30 head = slow->next; 31 slow->next = NULL; 32 return head; 33 } 34 }; 35 36 int main() 37 { 38 39 return 0; 40 }
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4157381.html