單鏈表模板類

2021-06-07 02:34:12 字數 1639 閱讀 4121

鍊錶是最基本的資料結構,是一組不連續的資料的集合,鍊錶中每個結點除包含結點元素外,還包含下一結點的位址。對鍊錶可以實現插入、刪除、查詢以及顯示等操作。

/*

* 單鏈表模板類list.h

*/ #ifndef _list_h_

#define _list_h_

#include using namespace std;

template class list

; listnode *list;

void insert(listnode *&l, const type &x);

bool remove(listnode *&l, const type &x);

void display(listnode *l) const;

int size(listnode *l) const;

int at(listnode *l, int x, type &k) const;

};#endif

// 建構函式

template list::list()

// 利用陣列初始化鍊錶

template list::list(type x, int n)

}// 利用鍊錶初始化鍊錶

template list::list(const list*l)

}}// 析構函式

template list::~list()

}// 外部呼叫插入資料方法

template void list::insert(const type &x)

// 內部呼叫向list插入資料

template void list::insert(listnode *&l, const type &x)

// 刪除值為x的,刪除成功返回true,失敗返回false

template bool list::remove(const type &x)

template bool list::remove(listnode *&l, const type &x)

if(p)

return true;

}// 列印鍊錶元素

template void list::display() const

template void list::display(listnode *l) const

while(p)

}else

cout << "鍊錶不存在!" << endl;

}// 返回鍊錶中元素個數

template int list::size() const

template int list::size(listnode *l) const

}return s;}/*

* 根據索引值取鍊錶中的元素

* 如果索引值大於鍊錶的大小返回-1

* 否則將索引值處結點的值儲存在k中並返回1

*/template int list::at(int x, type &k) const

template int list::at(listnode *l, int x, type &k) const

else

k = p->data;

}return 1;

}

單鏈表 模板類

include using namespace std 宣告單鏈錶類模板 為了說明友元類 template class list 定義鍊錶結點類模板 template class listnode listnode type item data item next null public 成員函式 ...

單鏈表模板類

在單鏈表中必然需要定義乙個頭節點來指向鍊錶的第乙個元素,struct node public object mutable node m header 這樣直接定義會有乙個問題,頭節點的構造會呼叫t類的建構函式,這顯然時不需要的,解決方案如下 mutable struct public object...

C 模板類 單鏈表

c 作業,用模板類寫鍊錶,完成了對基本的單鏈表的插入,刪除等。include using namespace std templatestruct node templateclass linkedlist linkedlist t find int index 返回索引對應的值 void remo...