在 C++ 中将第一个元素移动到给定链表的末尾
在本教程中,我们将编写一个程序,将第一个元素移动到给定链表的末尾。
让我们看看解决问题的步骤。
初始化链表。
找到链表的最后一个节点。
将第二个节点作为新的头部。
更新第一个和最后一个节点的链接。
示例
让我们看看代码。
#include输出结果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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
10 除夕祝福语大全简短的
11 生日送祝福语简短独特
12 姐妹生日祝福语简短的话
13 六一条幅祝福语简短
14 母亲大寿祝福语简短霸气
15 生日贺卡祝福语短语简短
16 喜得孙子祝福语简短霸气
17 牛年的新年祝福语简短
18 送你甜甜的祝福语简短