服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++链表倒序实现方法

C++链表倒序实现方法

2021-01-29 14:18C++教程网 C/C++

这篇文章主要介绍了C++链表倒序实现方法,是一个很经典的C++链表操作实例,需要的朋友可以参考下

本文通过一个实例展示了C++实现链表倒序的方法,对于C++数据结构的学习有很好的参考借鉴价值。具体方法如下:

首先,C++链表倒序的难点在于如何一个个地修改。虽然不是数组,但是大概思想是一样的,所以可以用一个for循序,一个游标对应for循环里面的 i,只不过要记得前一个节点和后一个节点,尤其是后一个,因为修改之后就访问不到后面的,所以要记录。for每一个循环只改变所指向的那个节点的指针,这样既不会乱套了。

用一个for循环就非常好理解了,实例代码如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <iostream>
#include <cstdlib>
#include <ctime>
 
using namespace std;
 
//链表节点类
class Node
{
private:
  int m_data;
  Node* m_next;
 
  Node(Node&) {}    //copy constructor is not allowed
 
public:
  explicit Node(int val = 0) : m_data(val), m_next(NULL) {}
  int getData() const { return m_data; }
  void setData(int val) { m_data = val; }
  Node* getNext(void) const { return m_next; }
  void setNext(Node* p) { m_next = p; }
};
 
//链表
class MyList
{
private:
  Node* m_head;  //pionter to the first node of the list
  Node* m_tail;  //poinoer to the last node of the list
 
  MyList(MyList&) {}
public:
  explicit MyList() : m_head(NULL), m_tail(NULL) {}
  void addNode(Node* pNode);
  void show(void) const;
  void reverse(void);
  void clean(void);
};
 
void MyList::addNode(Node* pNode)
{
  if (m_head)
  {
    m_tail->setNext(pNode);
    m_tail = pNode;
  }
  else    //blank list
  {
    m_head = pNode;
    m_tail = pNode;
  }
}
 
void MyList::show(void) const
{
  Node* pNode = m_head;
  while (pNode)
  {
    std::cout << pNode->getData() << "  ";
    pNode = pNode->getNext();
  }
}
 
void MyList::reverse(void)
{
  Node* preNode = NULL;    //下面游标的前一个
  Node* pNode ;    //指向每一个节点,相当于游标
  Node* afterNode;    //上面游标的上一个
 
  for (pNode = m_head; pNode != NULL; pNode = afterNode)  //这里的每次循环对应一个节点,本质上和数组原理差不多
  {
    afterNode = pNode->getNext();
    pNode->setNext(preNode);
    preNode = pNode;
  }
 
  pNode = m_head;  //交换头尾指针
  m_head = m_tail;
  m_tail = pNode;
}
 
void MyList::clean(void)
{
  if (m_head)
  {
    Node* pNode = m_head;
    Node* pTemp;
    while (pNode)
    {
      pTemp = pNode->getNext();
      delete pNode;
      pNode = pTemp;
    }
 
    m_head = m_tail = NULL;
  }
}
 
int main(void)
{
  MyList listHead;
 
  srand((unsigned)time(NULL));
  for (int i = 0; i < 9; i++)
  {
    int temp = rand() % 50;
    Node* pNode = new Node(temp);
    listHead.addNode(pNode);
  }
  listHead.show();
 
  listHead.reverse();
  cout << endl;
  listHead.show();
  listHead.clean();
  listHead.show();
  
  system("pause");
}

相信本文实例对大家学习C++数据结构与算法能起到一定的参考借鉴作用。

延伸 · 阅读

精彩推荐