标签:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULL
and k =2
,
return4->5->1->2->3->NULL
.
解题思路:
双指针(tail,pre)找到链表的尾部和总长度,使用pre走 (len-k%(len)-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==NULL||head->next==NULL)return head; ListNode *tail,*pre; tail=pre=head; int len=1; while(tail->next!=NULL) //找到尾部 { tail=tail->next; len++; } int i=len-(k%(len))-1; //考虑k数据的过大 while(i>0) { i--; pre=pre->next; } tail->next=head; head=pre->next; pre->next=NULL; return head; } };
标签:
原文地址:http://www.cnblogs.com/aorora/p/4330737.html