链栈和链队
2011-01-02 14:50 Clingingboy 阅读(735) 评论(0) 编辑 收藏 举报
基本的栈
class Stack { char base[STACK_SIZE]; int top; public: Stack(){ top=-1;} void push(char str) { base[++top]=str; } char pop() { return base[top--]; } bool empty() { return top == -1; } bool full() { return top==STACK_SIZE-1; } void display() { while(!empty()) { char current=pop(); cout << current << endl; } } };
逆波兰表达式
优点:不会发生内存溢出的问题
链栈
通过链表操作头结点就可以了
class LinkStack { private: LinkList* list; public: LinkStack(){list=new LinkList();} void Push(int iData) { list->InsertFirst(iData); } int Pop() { return list->DeleteFirst()->iData; } bool IsEmpty() { return list->IsEmpty(); } void Test() { this->Push(1); this->Push(2); this->Push(3); this->Push(4); this->Pop(); this->Pop(); this->Pop(); this->Pop(); } };
Queue
需要一个头和尾,两者相当于入队时,rear++,出队时front++,当front等于rear时,则表示为空.
基本的队列
class IntQueue { int base[STACK_SIZE]; int front,rear; public: IntQueue(){ front=0;rear=-1;} void EnQueue(int iData) { base[++rear]=iData; } int DeQueue() { return base[front++]; } bool Empty() { return front==rear; } void Test() { EnQueue(1); EnQueue(2); EnQueue(3); EnQueue(4); DeQueue(); DeQueue(); DeQueue(); DeQueue(); } };
环形队列
(1)为了防止队满的情况
如1,2,3,4,5,MaxSize=5,当插入元素6,则溢出,当用了环形队列,那么就变成了6,2,3,4,5(6替换了1)
rear=(rear+1)%STACK_SIZE;
(2)在出对时判断是否队为空
(3)在入队时判断是否队满
改进后的代码
class IntQueue { int base[STACK_SIZE]; int front,rear; public: IntQueue(){ front=0;rear=-1;} void EnQueue(int iData) { if(IsFull() && rear>0) return; rear=(rear+1)%STACK_SIZE; base[rear]=iData; } int DeQueue() { if(Empty()) return 0; int val=base[front]; front=(front+1)%STACK_SIZE; return val; } bool Empty() { return front==rear; } bool IsFull() { return (rear+1)%STACK_SIZE==front; } void Test() { EnQueue(1); EnQueue(2); EnQueue(3); EnQueue(4); DeQueue(); DeQueue(); DeQueue(); DeQueue(); } };
链队
用双端链表实现,每次插入都是插入尾结点,删除则是删除头结点
class LinkQueue { private: LinkList* list; public: LinkQueue(){list=new LinkList();} void Enqueue(int iData) { list->InsertLast(iData); } int Dequeue() { return list->DeleteFirst()->iData; } bool IsEmpty() { return list->IsEmpty(); } void Test() { this->Enqueue(1); this->Enqueue(2); this->Enqueue(3); this->Enqueue(4); this->Dequeue(); this->Dequeue(); this->Dequeue(); this->Dequeue(); } };