小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
给定一个单链表,将链表逆时针旋转 k 个节点。其中 k 是给定的正整数。例如,如果给定的链表是 10->20->30->40->50->60 且 k 为 4,则该链表应修改为 50->60->10->20->30- > 40。假设 k 小于链表中的节点数。
方法一:
要旋转链表,我们需要将第k个节点的next改为NULL,将最后一个节点的next改为上一个头节点,最后将head改为第(k+1)个节点。所以我们需要掌握三个节点:第k个节点、第(k+1)个节点和最后一个节点。
从头开始遍历列表并在第 k 个节点处停止。存储指向第 k 个节点的指针。我们可以使用 kthNode->next 得到第 (k+1) 个节点。继续遍历直到最后并存储指向最后一个节点的指针。最后,如上所述更改指针。
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void rotate(Node** head_ref, int k)
{
if (k == 0)
return;
Node* current = *head_ref;
int count = 1;
while (count < k && current != NULL) {
current = current->next;
count++;
}
if (current == NULL)
return;
Node* kthNode = current;
while (current->next != NULL)
current = current->next;
current->next = *head_ref;
*head_ref = kthNode->next;
kthNode->next = NULL;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
int main(void)
{
Node* head = NULL;
for (int i = 60; i > 0; i -= 10)
push(&head, i);
cout << "Given linked list \n";
printList(head);
rotate(&head, 4);
cout << "\nRotated Linked list \n";
printList(head);
return (0);
}
输出:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
时间复杂度:O(n),其中 n 是链表中的节点数。代码只遍历链表一次。
如果您发现任何不正确的内容,或者您想分享有关上述主题的更多信息,请发表评论。
方法2:
将链表旋转k,我们可以先使链表循环,然后从头节点向前移动k-1步,使第(k-1)个节点紧挨着空,并以第k个节点为头。
#include <bits/stdc++.h>
using namespace std;
、
class Node {
public:
int data;
Node* next;
};
void rotate(Node** head_ref, int k)
{
if (k == 0)
return;
Node* current = *head_ref;
while (current->next != NULL)
current = current->next;
current->next = *head_ref;
current = *head_ref;
for (int i = 0; i < k - 1; i++)
current = current->next;
*head_ref = current->next;
current->next = NULL;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
int main(void)
{
Node* head = NULL;
for (int i = 60; i > 0; i -= 10)
push(&head, i);
cout << "Given linked list \n";
printList(head);
rotate(&head, 4);
cout << "\nRotated Linked list \n";
printList(head);
return (0);
}
输出:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
🥇 往期优质文章
数据结构单链表之链表介绍 | 第一套
数据结构单链表之链表与数组 | 第二套
数据结构单链表之链表插入 | 第三套
数据结构单链表之删除节点 | 第四套
数据结构单链表之删除给定位置的链表节点 | 第五套
数据结构单链表之查看数组与链表的方法 | 第六套-1
数据结构单链表之查看数组与链表的方法 | 第六套-2
数据结构单链表之查找链表的长度(迭代和递归) | 第七套
数据结构单链表之交换链表中的节点而不交换数据 | 第八套
数据结构单链表之反转链表 | 第九套
数据结构单链表之合并两个已排序的链表 | 第十套
数据结构单链表之链表的归并排序 | 第十一套
数据结构单链表之以给定大小的组反转链表 | 第十二套
数据结构单链表之检测和删除链表中的循环 | 第十三套
数据结构单链表之将链表表示的两个数字相加 | 第十四套
📣尾注: 想要获取更多数据结构相关的知识,你可以关注我:海拥,我希望你觉得这篇文章有帮助。
如果你看到这里,感谢你的阅读 :)
💌 欢迎大家在评论区提出意见和建议!💌
如果你真的从这篇文章中学到了一些新东西,喜欢它,收藏它并与你的小伙伴分享。🤗最后,不要忘了❤或📑支持一下哦。