反转链表
Posted pengwang52
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反转链表相关的知识,希望对你有一定的参考价值。
#include<iostream> #include <stack> #include <algorithm> #include <string> using namespace std; typedef struct ListNode { int data; struct ListNode* next; ListNode(int data = 0, struct ListNode* next = NULL) : data(data), next(next) {} } ListNode; ListNode* construct_list_node() { int n = 10; ListNode* head = NULL; head = new ListNode(n); ListNode* p = head; while (--n) { p->next = new ListNode(n); p = p->next; } return head; } ListNode* reverse_list(ListNode* phead) { ListNode* reverse_phead = nullptr; ListNode* pcur_node = phead; ListNode* pre_node = nullptr; while (pcur_node != nullptr) { ListNode* pNext= pcur_node->next; // 注意操作都是在 pcur_node if (pNext == nullptr) { reverse_phead = pcur_node; } pcur_node->next = pre_node; pre_node = pcur_node; pcur_node = pNext; } return reverse_phead; } int main() { ListNode* head = construct_list_node(); ListNode* pre = head; while(pre != nullptr) { cout << pre->data << endl; pre = pre->next; } cout << " "; cout << " "; cout << " "; ListNode* reverse_phead = reverse_list(head); pre = reverse_phead; while(pre != nullptr) { cout << pre->data << endl; pre = pre->next; } return 0; }
以上是关于反转链表的主要内容,如果未能解决你的问题,请参考以下文章