Đưa ra một danh sách được liên kết, chúng ta phải di chuyển phần tử cuối cùng lên phía trước. Hãy xem một ví dụ.
Đầu vào
1 -> 2 -> 3 -> 4 -> 5 -> NULL
Đầu ra
5 -> 1 -> 2 -> 3 -> 4 -> NULL
Thuật toán
-
Khởi tạo danh sách liên kết.
- Quay lại nếu danh sách được liên kết trống hoặc có một nút.
-
Tìm nút cuối cùng và nút cuối cùng thứ hai của danh sách được liên kết.
-
Đặt nút cuối cùng làm nút mới.
-
Cập nhật liên kết của nút cuối cùng thứ hai.
Thực hiện
Sau đây là cách thực hiện thuật toán trên trong 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;
} Đầu ra
Nếu bạn chạy đoạn mã trên, thì bạn sẽ nhận được kết quả sau.
1->9->8->7->6->5->4->3->2->NULL