当前位置:编程学习 > C/C++ >>

C++自己实现list

 

  前两个博客发表了自己写的stack(栈)和queue(队列),感觉比较简单,今天想试着实现list,结果发现,不是那么容易,感觉自己对STL的底层不是很了解,

 

真要自己实现还真的很难,看STL的源代码,那个晕啊...那代码也写得太难理解了,当然跟我不了解有关,但我相信,在将来的某一天我会懂的,你看我的代码也会懂的。

 

  话说:STL中的list的内部结构就是一个双向链表,这个东东以前还真没有玩过,就凭他用的是双向链表我就不想用他,指针太多,耗资源,当然存在就有他的价值,

 

他能快速访问其中的元素。废话总该少说,代码就该多些。

 

  有那么一点高兴的是实现双向链表的翻转,其他的没什么了,list还没有实现,由于现在能力有限,新的版本一定会发布的,你就将就着看吧!

 

源码

#include <iostream>

using namespace std;

template<typename T>

class list {   

public :        list()       

{           

initialize();       

}       

list(int count)       

{            

initialize();           

if(count>0)           

{               

for(int i=0;i<count;i++)               

{                   

push_front(0);               

}           

}       

}       

list(int count,T data)       

{           

initialize();           

if(count>0)           

{               

for(int i=0;i<count;i++)                

{                   

push_front(data);               

}           

}       

}       

//显示最后一个节点       

T& back()       

{           

checkEmpty();           

return cur->data;       

 }       

T& back() const       

{           

return back();       

}       

//显示第一个节点       

T& front()       

{           

checkEmpty();           

return head->next->data;       

}       

T& front() const       

{           

return front();      

 }       

//弹出最后一个节点       

void pop_back()       

{           

checkEmpty();           

cur=cur->prev;           

delete cur->next;           

cur->next=NULL;           

--len;       

}       

//弹出第一个节点       

void pop_front()       

{           

checkEmpty();           

node* tmp=head->next;           

head->next=tmp->next;           

tmp->prev=head;           

delete tmp;           

--len;       

}       

//前插节点       

void push_front(const T& t)       

{           

node* newNode=new node(t);           

head->next=newNode;           

newNode->prev=head;           

++len;       

}       

//后插节点       

void push_back(const T& t)   

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,