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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(!head || !k || !head->next) return head; ListNode *p, *q=head, *r; int l=0, i; for(p=head; p; p=p->next) l++; k = k%l; for(i=0; i<k; i++) { if(!q->next) q = head; else q = q->next; } p=head; while(q->next) { p = p->next; q = q->next; } r = p->next; if(!r) return head; p->next = NULL; q->next = head; return r; } };
2.
先连成环,算长度。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(!head || !k) return head; ListNode *p, *q=head, *r; int l=1, i; for(p=head; p->next; p=p->next) l++; p->next = head; k = l-k%l; for(i=0; i<k; i++) p = p->next; head=p->next; p->next=NULL; return head; } };