在C++中實現鏈表節點的反轉可以通過迭代或遞歸兩種方法來實現。以下是其中一種方法的示例代碼:
#include <iostream>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void printList(ListNode* head) {
while (head != NULL) {
std::cout << head->val << " ";
head = head->next;
}
std::cout << std::endl;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
std::cout << "Original list: ";
printList(head);
head = reverseList(head);
std::cout << "Reversed list: ";
printList(head);
return 0;
}
該示例代碼中定義了一個節點結構體ListNode
,并實現了reverseList
函數來反轉鏈表。通過調用reverseList
函數并打印結果,可以看到鏈表節點的順序被成功反轉。