LeetCode 61. 旋转链表 | C语言版
LeetCode 61. 旋转链表
题目描述
题目地址:61. 旋转链表
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
解题思路
思路一:使用指针
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
if(head==NULL || k==0) return head;
int n=0;
//链表尾结点
struct ListNode* tail;
//计算链表长度n
for(struct ListNode* i=head;i;i=i->next){
tail=i;
n++;
}
k=k%n;
struct ListNode* p=head;
for(int i=0;i<n-k-1;i++){
//将链表的第n-k+1个节点设置成p
p=p->next;
}
//将链表连成环
tail->next=head;
//将链表从新的地方断开
//换头
head=p->next;
p->next=NULL;
return head;
}
运行结果
参考文章:
思路二:减少遍历节点数
代码实现
在这里插入代码片