以下是在C++中逆轉單鏈表的示例代碼:
#include <iostream>
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* reverseLinkedList(Node* head) {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;
while (current != nullptr) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void printLinkedList(Node* node) {
while (node != nullptr) {
std::cout << node->data << " ";
node = node->next;
}
std::cout << std::endl;
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
std::cout << "Original Linked List: ";
printLinkedList(head);
head = reverseLinkedList(head);
std::cout << "Reversed Linked List: ";
printLinkedList(head);
return 0;
}
在這個示例中,我們定義了一個簡單的Node
結構來表示鏈表的節點,并實現了reverseLinkedList
函數來反轉鏈表。我們還實現了printLinkedList
函數來打印鏈表的內容。在main
函數中,我們創建了一個包含三個節點的鏈表,并打印出原始鏈表和反轉后的鏈表。