堆 鍊錶實現

2021-06-29 03:40:47 字數 2475 閱讀 6108

小頂堆大頂堆的概念大家應該都很熟悉了,如果不了解,可以搜尋一下,網上很多介紹,而且很多原始碼實現,都很簡單。

不過從網上看了一些堆的實現,都是用陣列的。但是陣列有乙個缺陷,需要擴充套件時,就要複製原來的記憶體,申請新的空間。所以我在想能不能用鍊錶,發現還真可以,就湊湊寫了個**。最後**是寫完了,發現其實鍊錶沒有必要,而且會占用更多的記憶體,尤其是對於那種int型變數,過多的指標真是浪費了大量記憶體。如果真要優化,可以針對陣列做優化,鍊錶不是出路。

反正**寫完了,拿出來晾一晾,呵呵。

**在vs2008上編譯測試通過,不過測試用例很簡單。

#ifndef _hnwyllmm_heap_h

#define _hnwyllmm_heap_h

#include #include #include template>

class cheap

~cheap()

int init()

int destroy()

m_root = m_last = null ;

m_count ;

} int size() const

int push(const elem_t &ele)

else if (parent->_left == m_last)

// parent's right child

else if (parent->_next)

else

m_last->_next = node ;

node->_parent = parent ;

node->_prev = m_last ;

m_last = node ;

} // 調整

cheap_node *next = m_last ;

cheap_node *parent = null ;

while ((parent = next->_parent) &&

m_cmp_func(next->_data, parent->_data)

)return 0 ; }

int pop(elem_t &ele)

m_root->_data = m_last->_data ;

m_last->_data = null ;

if (m_last->_parent)

else

}m_last = m_last->_prev ;

delete m_last->_next ;

m_last->_next = null ;

for (cheap_node *last = m_root, *node = null ; last ; last = node)

else

node = last->_right ;

}else

node = last->_left ;

if (node)

else

break ;

}}

return 0 ;

} friend cheap &operator <<(cheap &heap, const elem_t &ele)

friend cheap &operator >>(cheap &heap, elem_t &ele)

void dump(std::ostream &os)

}os << std::endl ; }

private:

// 堆中的乙個節點

// 包含了樹的結構和鍊錶的結構

// 還有乙個資料

class cheap_node

~cheap_node()

};private:

cheap_node * m_root ; // 第乙個資料

cheap_node * m_last ; // 最後乙個資料

int m_count ; // 統計個數

cmp_func_t m_cmp_func ; // 用來做比較的函式

};#endif // _hnwyllmm_heap_h

測試檔案:

main.cpp

#include #include "heap_array.h"

using namespace std ;

int main(void)

return 0 ;

}

小頂堆大頂堆的概念大家應該都很熟悉了,如果不了解,可以搜尋一下,網上很多介紹,而且很多原始碼實現,都很簡單。

但是從網上看了一些堆的實現,都是用陣列的。但是陣列有乙個缺陷,需要擴充套件時,就要複製原來的記憶體,申請新的空間。所以我在想能不能用鍊錶,發現還真可以,就湊湊寫了個**。最後**是寫完了,發現其實鍊錶沒有必要,而且會占用更多的記憶體,尤其是對於那種int型變數,過多的指標真是浪費了大量記憶體。

反正**寫完了,拿出來晾一晾,呵呵。

**在vs2008上編譯測試通過,不過測試用例很簡單。

分別用陣列和鍊錶實現堆

為了更好的理解棧的原理,本文分別用陣列和鍊錶實現了棧,關於堆和棧的區別可參考文章 1 陣列實現棧 brife 陣列實現棧類 include ifndef arraystack h define arraystack h const uint defualf stack size 3 template...

BZOJ 1150 (堆 鍊錶)

你在一家 it 公司為大型寫字樓或辦公樓 offices 的計算機資料做備份。然而資料備份的工作是枯燥乏味 的,因此你想設計乙個系統讓不同的辦公樓彼此之間互相備份,而你則坐在家中盡享計算機遊戲的樂趣。已知辦公 樓都位於同一條街上。你決定給這些辦公樓配對 兩個一組 每一對辦公樓可以通過在這兩個建築物之...

鍊錶 java實現雙向鍊錶

前面已經總結了單向鍊錶,有興趣的兄弟可以進我部落格看一下。大家對比就可以看出,實現同樣的功能單向鍊錶要比雙向鍊錶痛苦的多。所以呀不斷地總結前輩留下的東西,是社會進步的基礎呀。可以直接看linkedlist的原始碼,其就是個雙向鍊錶。一 雙向鍊錶的結構。1 首先節點的結構,其中包含本節點內容,同時需要...