基于链表的栈和队列
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; }
相关文章推荐
- 基于链表实现Java 自定义Queue队列
- 基于链表、数组实现队列、循环队列
- 基于jdk的list 和 队列 linkedList 和父亲长子兄弟链表模型 实现的 树 的前序遍历,后序遍历和层次遍历
- C语言基于链表的队列
- 基于链表的队列实现
- 自己写的基于链表的并发安全队列模板类concurrent_queue
- 基于数组的循环队列和基于链表的队列
- 自己动手构建无锁的并发容器(续篇)——基于单向链表实现的无锁队列
- 基于链表实现队列
- Java 基于链表的队列创建
- 基于链表的队列、基于顺序表的队列 C语言
- 【数据结构练习】基于链表结构实现的队列
- 算法与数据结构(二) 基于链表的队列
- java基于有序链表的优先级队列实现
- java中(基于链表)队列的实现
- Java算法系列3--基于链表自定义队列
- 典型数据结构--基于链表的队列实现
- 基于链表及环形队列的生产者与消费者简单实现