国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++鏈表倒序實現方法

2020-01-26 15:23:15
字體:
來源:轉載
供稿:網友

本文通過一個實例展示了C++實現鏈表倒序的方法,對于C++數據結構的學習有很好的參考借鑒價值。具體方法如下:

首先,C++鏈表倒序的難點在于如何一個個地修改。雖然不是數組,但是大概思想是一樣的,所以可以用一個for循序,一個游標對應for循環里面的 i,只不過要記得前一個節點和后一個節點,尤其是后一個,因為修改之后就訪問不到后面的,所以要記錄。for每一個循環只改變所指向的那個節點的指針,這樣既不會亂套了。

用一個for循環就非常好理解了,實例代碼如下所示:

#include <iostream>#include <cstdlib>#include <ctime>using namespace std;//鏈表節點類class Node{private:  int m_data;  Node* m_next;  Node(Node&) {}    //copy constructor is not allowedpublic:  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++數據結構與算法能起到一定的參考借鑒作用。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武隆县| 津市市| 潼南县| 亚东县| 晋州市| 将乐县| 永年县| 伊宁县| 海阳市| 迭部县| 翼城县| 灌云县| 安多县| 贵德县| 紫阳县| 平乐县| 勃利县| 阿克陶县| 科尔| 封丘县| 张家港市| 伊吾县| 武城县| 中宁县| 永春县| 建水县| 黑山县| 象山县| 新沂市| 类乌齐县| 乌审旗| 萝北县| 秭归县| 化州市| 崇明县| 镇原县| 当雄县| 城步| 奈曼旗| 乐山市| 鹤岗市|