將連結串列中最後一個元素移動到開頭
給定一個連結串列,我們需要將最後一個元素移動到開頭。我們來看一個示例。
輸入
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