本文通過一個實例展示了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++數據結構與算法能起到一定的參考借鑒作用。
新聞熱點
疑難解答
圖片精選