這篇文章主要介紹了C++如何使用模板實現一個List,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
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 -- ;
//刪除頭節點
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;
}
};調用方式如下
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;
}感謝你能夠認真閱讀完這篇文章,希望小編分享的“C++如何使用模板實現一個List”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。