将链表中的第一个元素移至末尾,使用 C++
<
给定一个链表,我们要将第一个元素移至末尾。我们来看一个示例。
输入
1 -> 2 -> 3 -> 4 -> 5 -> NULL
输出
2 -> 3 -> 4 -> 5 -> 1 -> 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* firstNode = *head;
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
*head = firstNode->next;
firstNode->next = NULL;
lastNode->next = firstNode;
}
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;
}输出
如果你运行以上代码,则会得到以下结果。
8->7->6->5->4->3->2->1->9->NULL
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP