C++ 使用模板實現(xiàn)一個List的實例
更新時間:2017年05月25日 09:08:57 投稿:lqh
這篇文章主要介紹了 C++ 使用模板實現(xiàn)一個List的實例的相關(guān)資料,需要的朋友可以參考下
C ++使用模板寫的一個List
template<class T>
class List
{
private:
struct Node
{
T data;
Node *next;
};
//head
Node *head;
//size
int length;
//process
Node *p;
//temp
Node *q;
public:
List()
{
head = NULL;
length = 0;
p = NULL;
}
void add(T t)
{
if(head == NULL)
{
q = new Node();
q->data = t;
q->next = NULL;
length ++ ;
head = q ;
p = head;
}
else
{
q = new Node();
q->data = t;
q->next = NULL;
length ++;
p -> next = q;
p = q;
}
}
void remove(int n)
{
if(n >= length )
{
return;
}
length -- ;
//刪除頭節(jié)點
if(n == 0)
{
q = head ;
head = head -> next;
delete(q);
}
else
{
q = head;
for(int i = 0 ; i < n-1 ; i++)
{
q = q -> next;
}
Node *t = q ->next;
q->next = q->next ->next;
delete(t);
}
//
p = head;
if (p != NULL)
{
while(p->next != NULL)
{
p = p->next;
}
}
}
int getSize()
{
return length;
}
int getLength()
{
return getSize();
}
T get(int n)
{
q = head;
for (int i = 0 ;i < n ; i++)
{
q = q->next;
}
return q->data;
}
};
調(diào)用方式如下
List<Stu>list;
Stu stu1;
Stu stu2;
Stu stu3;
stu1.username = "1";
stu2.username = "2";
stu3.username = "3";
list.add(stu1);
list.remove(0);
list.add(stu2);
list.add(stu3);
for (int i = 0 ;i < list.getSize() ; i ++)
{
cout << list.get(i).username;
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C++數(shù)據(jù)結(jié)構(gòu)之實現(xiàn)循環(huán)順序隊列
這篇文章主要介紹了 C++數(shù)據(jù)結(jié)構(gòu)之實現(xiàn)循環(huán)順序隊列的相關(guān)資料,需要的朋友可以參考下2017-01-01
C++ Vector 動態(tài)數(shù)組的實現(xiàn)
這篇文章主要介紹了C++ Vector 動態(tài)數(shù)組的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
C++實現(xiàn)折半插入排序(BinaryInsertSort)
這篇文章主要為大家詳細(xì)介紹了C++實現(xiàn)折半插入排序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-04-04
C語言數(shù)據(jù)結(jié)構(gòu)與算法之鏈表(一)
鏈表是線性表的鏈?zhǔn)酱鎯Ψ绞健f湵淼膬?nèi)存是不連續(xù)的,前一個元素存儲地址的下一個地址中存儲的不一定是下一個元素。小編今天就將帶大家深入了解一下鏈表,快來學(xué)習(xí)吧2021-12-12

