给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4 输出:[2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]
内 -100 <= Node.val <= 100
0 <= k <= 2 * 10^9
思路:把链表拆开成两部分,再拼接
用双指针同时移动确定拆开位置
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int getlength(struct ListNode *head){
int n=0;
while(head){
n++;
head=head->next;
}return n;
}
struct ListNode* rotateRight(struct ListNode* head, int k) {
if(head==NULL) return head;
int n=getlength(head);
k%=n;
if(k==0) return head;
struct ListNode *p=head,*q=head;//开始确定位置
for(int i=0;i<=k;i++) p=p->next;
while(p) p=p->next,q=q->next;//p指向空的时候,q指向的位置就是分开的位置
p=q->next;
q->next=NULL;
q=p;
while(q->next!=NULL)q=q->next;
q->next=head;
return p;
}