在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
函数并打印结果,可以看到链表节点的顺序被成功反转。