链表反转,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 << "\t";
48     }
49     std::cout << "\n";
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 << "\t";
55     }
56     std::cout << "\n";
57 
58     return 0;
59 }

 

posted on 2020-09-13 22:48  _bob  阅读(317)  评论(0编辑  收藏  举报