資料結構 筆記:單鏈表的遍歷與優化
阿新 • • 發佈:2018-11-10
如何遍歷單鏈表中的每一個數據元素?
為單鏈表提供新的方法,線上性時間內完成遍歷
設計思路(遊標)
-在單鏈表的內部定義一個遊標(Node* m_current)
-遍歷開始前將遊標指向位置為0的資料元素
-獲取遊標指向的資料元素
-通過結點中的next指標移動遊標
提供一組遍歷相關的函式,以線性的時間複雜度遍歷連結串列
函式 | 功能說明 |
move() | 將遊標定位到目標位置 |
next() | 移動遊標 |
current() | 獲取遊標所指向的資料元素 |
end() | 遊標是否到達尾部(是否為空) |
遍歷函式原型設計
-bool move(int i,int step = 1)
-bool end();
-T current();
-bool next();
bool move(int i,int step = 1) { bool ret = (0 <= i)&& (i< m_length) && (step >0); if(ret) { m_current = position(i)->next; m_step = step; } return ret; } bool end() { return (m_current == NULL); } T current() { if(!end()) { return m_current->value; } else { //丟擲異常 } } bool next() { int i = 0; while((i < m_step) && !end()) { m_current = m_current->next; i++; } return (i == m_step); }
總結:
單鏈表的遍歷需要線上性時間內完成
-在單鏈表內部定義遊標變數,通過遊標變數提高效率
-遍歷相關的成員函式是相互依賴,相互配合的關係
-封裝結點的申請和刪除操作更有利於增強擴充套件性