Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
- 定义两个指针,分布指向 list 的头结点和尾结点,
- 将头结点插到尾部
代码:
class Solution { public: ListNode* rotateRight(ListNode* head, int k) { ListNode *h1=head; ListNode *h2=head; if(k==0||head==NULL) return h1; int l=1; while(h1&&h1->next) { h1=h1->next; l++; } // if(l>1) int c=l-k%l; // cout<<h1->val<<endl; // cout<<l<<endl; // cout<<c<<endl; if(l==1) return head; for(int i=0;i<c;i++) { ListNode *t=h2; h2=h2->next; cout<<h2->val<<endl; cout<<t->val<<endl; h1->next=t; h1=t; t->next=NULL; } return h2; } };