my_list
記錄資料結構連結串列學習過程(手寫list)
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef int Rank;
template<typename T> struct ListNode{
T data; //資料域
ListNode<T> *prev;//前驅
ListNode<T> *next;//後繼
ListNode() {};
ListNode(T e,ListNode p=NULL,ListNode q=NULL)
:data(e),prev(p),next(q) {}//預設構造(方便賦值)
};
template<typename T> class my_list{
private:
int _size; //元素個數
ListNode<T> *header;//頭指標
ListNode<T> *trailer;//尾指標
void init(); //初始化
public:
my_list(){init();}//預設構造
~my_list(); //析構
T& operator[] (Rank ) const; //過載[]運算子
Rank size() const {return _size;} //大小
bool empty() const {return _size<=0;}//判斷是否為空
void my_clear(); //清空
ListNode<T>* getHeader(){return header;} //返回頭節點
ListNode<T>* getTrailer(){return trailer;}//返回尾節點
ListNode<T>* insert_prev(ListNode<T> *,int ); //頭插法
ListNode<T>* insert_next(ListNode<T> *,int ); //尾插法
T my_remove(ListNode<T> *); //刪除
ListNode<T>* my_find(T const& )const; //查詢
};
template<typename T> T& my_list<T>::operator[] (Rank r)const{
ListNode<T> *p=header->next;
while(0<r--){
p=p->next;
}
return p->data;
}
template<typename T> void my_list<T>::init(){
header=new ListNode<T>;
trailer=new ListNode<T>;
header->prev=NULL;
header->next=trailer;
trailer->prev=header;
trailer->next=NULL;
_size=0;
}
template<typename T> ListNode<T>* my_list<T>::insert_prev(ListNode<T> *p,int e){
ListNode<T> *temp=new ListNode<T>;
temp->data=e;
temp->prev=p->prev;
temp->next=p;
p->prev->next=temp;
p->prev=temp;
_size++;
return temp;
}
template<typename T> ListNode<T>* my_list<T>::insert_next(ListNode<T> *p,int e){
ListNode<T> *temp=new ListNode<T>;
temp->data=e;
temp->prev=p;
temp->next=p->next;
p->next->prev=temp;
p->next=temp;
_size++;
return temp;
}
template<typename T> T my_list<T>::my_remove(ListNode<T> *p){
p->next->prev=p->prev;
p->prev->next=p->next;
T e=p->data;
delete p;
_size--;
return e;
}
template<typename T> void my_list<T>::my_clear(){
while(0<_size--){
my_remove(header->next);
}
}
template<typename T> my_list<T>::~my_list(){
my_clear();
delete header;
delete trailer;
}
template<typename T> ListNode<T>* my_list<T>::my_find(T const& e)const{
ListNode<T> *p=header;
int n=_size;
while(0<n--){
if(e == (p=p->next)->data) return p;
}
return NULL;
}
int main(){
my_list<int> L;
ListNode<int> *h=L.getHeader();
for(int i=0;i<10;i++){
L.insert_next(h,i);
h=h->next;
}
for(ListNode<int> *p=L.getHeader()->next;p!=L.getTrailer();p=p->next)cout<<p->data<<" ";
cout<<endl;
cout<<L.size()<<endl;
L.my_remove(L.my_find(5));
cout<<L.size()<<endl;
for(ListNode<int> *p=L.getHeader()->next;p!=L.getTrailer();p=p->next)cout<<p->data<<" ";
cout<<endl;
cout<<L.empty()<<endl;
L.my_clear();
cout<<L.empty()<<endl;
return 0;
}
效果展示