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