标签:style blog color io for sp div on log
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
.
旋转链表:求出链表长度,确定k,k = k%len; 再仿照last-slow的思想,先让p指针走K步,然后q再开始走,当p->next为null时,q为旋转位。
1 * Definition for singly-linked list. 2 * struct ListNode { 3 * int val; 4 * ListNode *next; 5 * ListNode(int x) : val(x), next(NULL) {} 6 * }; 7 */ 8 class Solution { 9 public: 10 ListNode *rotateRight(ListNode *head, int k) { 11 12 if(k == 0 || !head) 13 return head; 14 ListNode *p=head, *q=head; 15 ListNode *l=head; 16 //模长度,求旋转步长 17 int len = 0; 18 while(l!=NULL){ 19 l = l->next; 20 len++; 21 } 22 k = k>len ? k%len : k; 23 //p先走K步,q再开始走 24 while(--k >= 0 && p != NULL){ 25 p = p->next; 26 } 27 28 if( p == NULL ) 29 return head; 30 31 while(p->next!=NULL){ 32 q = q->next; 33 p = p->next; 34 } 35 36 p->next = head; 37 head = q->next; 38 q->next = NULL; 39 40 return head; 41 } 42 };
标签:style blog color io for sp div on log
原文地址:http://www.cnblogs.com/crazelee/p/4051481.html