zoukankan      html  css  js  c++  java
  • 反转链表

    #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;
    }
  • 相关阅读:
    5. java 的类和对象
    java 的变量以及构造方法
    idea运行Test时为啥会运行两次
    MYSQL(三)
    MYSQL(二)
    MySql密码操作
    MYSQL(一)
    【数据结构】2.线性表及其结构
    【数据结构】1.数据结构及算法的入门
    推荐四款可视化工具,解决99%的可视化大屏需求
  • 原文地址:https://www.cnblogs.com/TMatrix52/p/12541910.html
Copyright © 2011-2022 走看看