- 思路:首先保留头结点 ,分为两段,一个已倒序的list,一个待处理的list.
- 代码如下:
#include<iostream> #include<functional> using namespace std; struct Node { int data = 0; Node* p_next = nullptr; }; Node* reverse_list(Node* head) { Node* p = head; head = nullptr; while (p) { Node* p_tmp = p; p = p->p_next; p_tmp->p_next = head; head = p_tmp; } return head; } void printList(Node* head) { while (head) { cout << head->data << '\t'; head = head->p_next; } cout << endl; } int main() { Node* p1 = new Node; p1->data = 1; Node* p2 = new Node; p2->data = 2; Node* p3 = new Node; p3->data = 3; Node* p4 = new Node; p4->data = 4; p3->p_next = p4; p2->p_next = p3; p1->p_next = p2; printList(p1); printList(reverse_list(p1)); delete p1; delete p2; delete p3; delete p4; }
- 运行结果如下:
单链表反转-c++
最新推荐文章于 2022-02-27 21:16:32 发布