C++ 模版雙向鏈表的實現詳解

來源:互聯網
上載者:User

代碼如下所示: 複製代碼 代碼如下:#include <iostream>
template <typename T>
class double_linked
{
struct node
{
T data;
node* prev;
node* next;
node(T t, node* p, node* n) : data(t), prev(p), next(n) {}
};
node* head;
node* tail;
public:
double_linked() : head( NULL ), tail ( NULL ) {}
template<int N>
double_linked( T (&arr) [N]) : head( NULL ), tail ( NULL )
{
for( int i(0); i != N; ++i)
push_back(arr[i]);
}
bool empty() const { return ( !head || !tail ); }
operator bool() const { return !empty(); }
void push_back(T);
void push_front(T);
T pop_back();
T pop_front();
~double_linked()
{
while(head)
{
node* temp(head);
head=head->next;
delete temp;
}
}
};
template <typename T>
void double_linked<T>::push_back(T data)
{
tail = new node(data, tail, NULL);
if( tail->prev )
tail->prev->next = tail;
if( empty() )
head = tail;
}
template <typename T>
void double_linked<T>::push_front(T data)
{
head = new node(data, NULL, head);
if( head->next )
head->next->prev = head;
if( empty() )
tail = head;
}
template<typename T>
T double_linked<T>::pop_back()
{
if( empty() )
throw("double_linked : list empty");
node* temp(tail);
T data( tail->data );
tail = tail->prev ;
if( tail )
tail->next = NULL;
else
head = NULL ;
delete temp;
return data;
}
template<typename T>
T double_linked<T>::pop_front()
{
if( empty() )
throw("double_linked : list empty");
node* temp(head);
T data( head->data );
head = head->next ;
if( head )
head->prev = NULL;
else
tail = NULL;
delete temp;
return data;
}
int main()
{
int arr[] = { 4, 6, 8, 32, 19 } ;
double_linked<int> dlist ( arr );
dlist.push_back( 11 );
dlist.push_front( 100 );
while( dlist )
std::cout << dlist.pop_back() << " ";
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.