思路:
1. 遍历链表找到结尾,顺便统计链表长度count
2. 将结尾指向head,使链表首位相连,并计算前行长度count=count-k%count
3. 前行count步,当前指针为尾,next为new head
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k) {
if (head==NULL||head->next==NULL){
return head;
}
struct ListNode *tail;
struct ListNode *p=head;
int count=1;
int newK;
while(p->next!=NULL){
p=p->next;
count++;
}
newK=k%count;
p->next=head;
count=count-newK;
p=head;
while(count-->1){
p=p->next;
}
tail=p;
head=p->next;
tail->next=NULL;
return head;
}

本文介绍了一种链表右旋算法的实现方法。通过遍历链表找到结尾并统计长度,然后调整链表结构使其首尾相连,最后重新定位头结点完成旋转。适用于需要对链表进行旋转操作的场景。
585

被折叠的 条评论
为什么被折叠?



