链式队列c++代码:
#include<iostream>
using namespace std;
typedef int ElemType;
struct QueueNode{
ElemType data;
QueueNode *next;
};
class ListQueue{
private:
QueueNode *front,*rear;
public:
ListQueue();
~ListQueue();
bool EnQueue(ElemType e);
bool DeQueue(ElemType *e);
bool Print();
};
inline ListQueue::ListQueue()
{
front = new QueueNode();
rear = front;
}
inline ListQueue::~ListQueue()
{
QueueNode *p;
while(front!=rear)
{
p = rear;
rear = rear->next;
delete p;
}
delete front;
}
bool ListQueue::EnQueue(ElemType e)//入队
{
QueueNode *s = new QueueNode();
if(!s)
return false;
s->data = e;
s->next = NULL;
rear->next = s;
rear = s;
return true;
}
bool ListQueue::DeQueue(ElemType *e)//出队
{
if(rear == front)
return false;
QueueNode *s = front->next;//当前节点
*e = s->data;
front->next = s->next;
if(rear == s)
rear = front;
delete s;
return true;
}
bool ListQueue::Print()
{
if(front == rear)
{
cout<<"队列为空!"<<endl;
return false;
}
cout<<"当前队列:";
QueueNode *s = front;
while(s != rear)
{
s = s->next;
cout<<s->data<<" ";
}
cout<<endl;
}
int main()
{
ListQueue *L = new ListQueue();
for(int i = 1;i<5;i++)
{
L->EnQueue(i);
}
L->Print();
for(int i = 1;i<5;i++)
{
ElemType k;
L->DeQueue(&k);
cout<<"出队元素:"<<k<<endl;
L->Print();
}
return 0;
}
链栈c++代码:
#include<iostream>
using namespace std;
typedef int ElemType;
struct StackNode{//节点类型
ElemType data;
StackNode *next;
};
class ListStack{
private:
StackNode *base,*top;
public:
ListStack();
~ListStack();
bool Push(ElemType e);
bool Pop(ElemType *e);
bool Print();
};
inline ListStack::ListStack()//初始化
{
base = new StackNode();//建一个head节点,里面不存放数据
base->next = NULL;
top = base;
}
inline ListStack::~ListStack()
{
StackNode *p;
while(top!=base)
{
p = top;
top = top->next;
delete p;
}
}
bool ListStack::Push(ElemType e)
{
StackNode *s = new StackNode();
if(!s)
return false;//内存申请失败
s->data = e;
s->next = top;
top = s;
return true;
}
bool ListStack::Pop(ElemType *e)
{
if(top == base)
return false;//栈为空
StackNode *p = top;
*e = p->data;
top = p->next;
delete p;
return true;
}
bool ListStack::Print()
{
if(top == base)
{
cout<<"栈为空!"<<endl;
return false;
}
cout<<"当前栈:";
StackNode *p = top;
while(p!=base)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
int main()
{
ListStack *L = new ListStack();
for(int i = 1;i<5;i++)
{
L->Push(i);
}
L->Print();
for(int i = 1;i<5;i++)
{
ElemType k;
L->Pop(&k);
cout<<"弹出元素:"<<k<<endl;
L->Print();
}
return 0;
}