• 链表反转,C++实现


     1 // To Compile and Run: g++ invert_list.cc -std=c++11 -Wall -O3 && ./a.out
     2 
     3 
     4 #include <iostream>
     5 #include <vector>
     6 
     7 
     8 class ListNode {
     9 public:
    10     int data;
    11     ListNode *pNext;
    12 
    13     ListNode()
    14     : data(0)
    15     , pNext(nullptr) {}
    16     ListNode(int i)
    17     : data(i)
    18     , pNext(nullptr) {}
    19 };
    20 
    21 
    22 ListNode *InvertList(ListNode *_pList) {
    23     ListNode *_pPrevious = nullptr;
    24     while (_pList != nullptr) {
    25         ListNode *tmpPtrNext = _pList->pNext;
    26 
    27         _pList->pNext = _pPrevious;
    28 
    29         _pPrevious = _pList;
    30         _pList = tmpPtrNext;
    31     }
    32 
    33     return _pPrevious;
    34 }
    35 
    36 int main(int argc, char const *argv[]) {
    37     const std::vector<int> arr {
    38         1, 2, 3
    39     };
    40     ListNode * const ROOT_PTR = new ListNode();
    41     ListNode *pList  = ROOT_PTR;
    42     for (int i: arr) {
    43         pList->pNext = new ListNode(i);
    44         pList = pList->pNext;
    45     }
    46     for (ListNode *p = ROOT_PTR->pNext; p != nullptr; p = p->pNext) {
    47         std::cout << p->data << "	";
    48     }
    49     std::cout << "
    ";
    50 
    51     pList = ROOT_PTR->pNext;
    52     ListNode *pNewRoot = InvertList(pList);
    53     for (ListNode *p = pNewRoot; p != nullptr; p = p->pNext) {
    54         std::cout << p->data << "	";
    55     }
    56     std::cout << "
    ";
    57 
    58     return 0;
    59 }
  • 相关阅读:
    ab命令做压测测试
    用js两张图片合并成一张图片
    Web全景图的原理及实现
    深入理解Java中的IO
    Spring AOP详解
    spring @Transactional注解参数详解
    优化MyBatis配置文件中的配置
    使用MyBatis对表执行CRUD操作
    @requestBody注解的使用
    url 拼接的一个模块furl
  • 原文地址:https://www.cnblogs.com/xiaochou/p/13663909.html
Copyright © 2020-2023  润新知