码迷,mamicode.com
首页 > 其他好文 > 详细

反转链表

时间:2020-03-21 21:21:36      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:reverse   head   algo   null   span   std   ever   main   div   

#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 << "\n";
    cout << "\n";
    cout << "\n";

    ListNode* reverse_phead = reverse_list(head);
    pre = reverse_phead;
    while(pre != nullptr) {
        cout << pre->data << endl;
        pre = pre->next;
    }

    return 0;
}

 

反转链表

标签:reverse   head   algo   null   span   std   ever   main   div   

原文地址:https://www.cnblogs.com/pengwang52/p/12541910.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!