c++ listnode反转方法分享

avatar
作者
筋斗云
阅读量:0

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!