将链表中最后一个元素移动到开头
给定一个链表,我们需要将最后一个元素移动到开头。我们来看一个示例。
输入
1 -> 2 -> 3 -> 4 -> 5 -> NULL
输出
5 -> 1 -> 2 -> 3 -> 4 -> NULL
算法
初始化链表。
- 如果链表为空或只有一个节点,则返回。
查找链表的最后一个节点和倒数第二个节点。
将最后一个节点作为新头。
更新倒数第二个节点的链接。
实现
以下是 C++ 中上述算法的实现
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void moveFirstNodeToEnd(struct Node** head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
struct Node* secondLastNode = *head;
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
secondLastNode = lastNode;
lastNode = lastNode->next;
}
secondLastNode->next = NULL;
lastNode->next = *head;
*head = lastNode;
}
void addNewNode(struct Node** head, int new_data) {
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = *head;
*head = newNode;
}
void printLinkedList(struct Node* node) {
while (node != NULL) {
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main() {
struct Node* head = NULL;
addNewNode(&head, 1);
addNewNode(&head, 2);
addNewNode(&head, 3);
addNewNode(&head, 4);
addNewNode(&head, 5);
addNewNode(&head, 6);
addNewNode(&head, 7);
addNewNode(&head, 8);
addNewNode(&head, 9);
moveFirstNodeToEnd(&head);
printLinkedList(head);
return 0;
}输出
如果您运行上面的代码,您将得到以下结果。
1->9->8->7->6->5->4->3->2->NULL
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP