您的位置:首页 > 其它

基于链表的栈和队列

2010-04-10 22:59 253 查看
#include <iostream>
#include <cstdlib>
#include <string>
#include <list>
#include <cassert>
#include <map>
#include <set>
#include <time.h>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
#define NULL 0

template<typename T>
class LinkList
{
class Node
{
public:
Node():next(NULL),prev(NULL){}
Node(const T& d):data(d),next(NULL),prev(NULL){}
T data;
Node *next;
Node *prev;
};
private:
Node *head;
unsigned _size;
public:
LinkList():head(new Node())
{
_size=0;
//point to itself
head->next=head;
head->prev=head;
}
void push_front(const T& v)
{
++_size;
Node *t=head->next;
Node *cur=new Node(v);
head->next=cur;
t->prev=cur;
cur->next=t;
cur->prev=head;
}
const T& front()
{
assert(!empty());
return head->next->data;
}
void pop_front()
{
--_size;
assert(!empty());
Node *cur=head->next;
head->next=cur->next;
cur->next->prev=head;
delete cur;
}
void push_back(const T& v)
{
++_size;
Node *t=head->prev;
Node *cur=new Node(v);
t->next=cur;
head->prev=cur;
cur->next=head;
cur->prev=t;
}
const T& back()
{
assert(!empty());
return head->prev->data;
}
bool empty()
{
return head->next==head;
}
void pop_back()
{
--_size;
assert(!empty());
Node *cur=head->prev;
cur->prev->next=head;
head->prev=cur->prev;
delete cur;
}
unsigned size()
{
return _size;
}
~LinkList()
{
Node *p=head->next;
while(p != head)
{
Node *temp=p->next;
delete p;
p=temp;
}
delete head;
}
};

template <typename T>
class Stack
{
public:
void push(const T& v)
{
list.push_back(v);
}
void pop()
{
list.pop_back();
}
bool empty()
{
return list.empty();
}
const T& top()
{
return list.back();
}
unsigned size()
{
return list.size();
}
private:
LinkList<T> list;
};

template <typename T>
class Queue
{
public:
void push(const T& v)
{
list.push_back(v);
}
void pop()
{
list.pop_front();
}
bool empty()
{
return list.empty();
}
const T& front()
{
return list.front();
}
unsigned size()
{
return list.size();
}
private:
LinkList<T> list;
};

int main()
{
//
stack<int,list<int> > s;
queue<int,list<int> > q;

//
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: