栈和队列的设计与实现
1.栈的设计与实现
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef char ElemType;
typedef struct Linknode
{
ElemType data;
struct Linknode *next;
}listack; //定义栈
void InStack(listack *&s)
{
s=(listack *)malloc(sizeof(listack));
s->next=NULL;
}//初始化栈
void DestoryStack(listack *&s)
{
listack *p=s,*q=s->next;
while(q!=NULL)
{
free(p);
p=q;
q=p->next;
}
free(p);
}//销毁栈
bool EmptyStack(listack *s)
{
return (s->next==NULL);
}//判断栈是否为空
void PushStack(listack *&s,ElemType e)
{
listack *p;
p=(listack *)malloc(sizeof(listack));
p->data=e;
p->next=s->next;
s->next=p;
}//进栈
bool PutStack(listack *&s,ElemType e)
{
listack *p;
if(s->next==NULL)
return false;
p=s->next;
e=p->data;
s->next=p->next;
free(p);
return true;
}//出栈
bool Gettop(listack *&s)
{
ElemType e;
if(s->next==NULL)
return false;
e=s->next->data;
printf("%c\n",e);
return true;
}//取栈顶
void StackLength(listack * s)
{
int length=0;
while(s->next!=NULL)
{
length++;
s->next=s->next->next;
}
printf("%d\n",length);
}//栈的长度
void DiStack(listack *s) //输出sq
{
if(s->next==NULL)
{
printf("这是一个空栈!");
printf("\n");
}
else
{
do
{
char ss=s->next->data;
printf("%c",ss);
s->next=s->next->next;
}while(s->next!=NULL);
}
}
void main()
{
listack *s;
char a1='a',b1='b',c1='c',d1='d',e1='e';
InStack(s);//1
EmptyStack(s);//2
PushStack(s,a1);
PushStack(s,b1);
PushStack(s,c1);
PushStack(s,d1);
PushStack(s,e1);//3
EmptyStack(s);//4
Gettop(s);//e
PutStack(s,a1);
Gettop(s);//d
PutStack(s,b1);
Gettop(s);//c
PutStack(s,c1);
Gettop(s);//b
PutStack(s,d1);
Gettop(s);//6
StackLength(s);//5
DiStack(s);
EmptyStack(s);//8
DestoryStack(s);//9
}
2.对列的设计与实现
/****************************顺序环形队列*****************************/
#include<stdio.h>
#include<malloc.h>
#include <stdlib.h>
#include <string.h>
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int front,rear;
} SqQueue; //建立队列
void CreateQueue(SqQueue* &q,ElemType a[],int n)
{
int i;
q->front=0;
for(i=1;i<=n;i++)
q->data[i]=a[i-1];
q->rear=n;
} //初始化队列
void InitQueue(SqQueue* &q)
{
q=(SqQueue *)malloc(sizeof(SqQueue));
q->front=q->rear=0;
} //销毁队列
void ClearQueue(SqQueue* &q)
{
free(q);
} //求队列的长度
void QueueLength(SqQueue *q)
{
printf("%d\n", q->rear-q->front);
} //判断队列是否为空
int QueueEmpty(SqQueue *q)
{
return(q->front==q->rear);
} //元素入队列
int EnQueue(SqQueue* &q,ElemType e)
{
if((q->rear+1)%MaxSize==q->front)
return 0;
q->rear=(q->rear+1)%MaxSize;
q->data[q->rear]=e;
return 1;
} //元素出队列
int DeQueue(SqQueue* &q)
{
ElemType e;
if(q->front==q->rear)
return 0;
q->front=(q->front+1)%MaxSize;
e=q->data[q->front];
printf("%c\n",e);
return 1;
} //显示队列中元素
void DispQueue(SqQueue *q)
{
int i;
for(i=q->front+1;i<=q->rear;i++)
printf("%c",q->data[i]);
printf("\n");
}
//主函数
int main()
{
SqQueue* q;
ElemType a[3]={'a','b','c'};
InitQueue(q);
QueueEmpty(q);
CreateQueue(q, a,3);
DeQueue(q);
QueueLength(q);
ElemType b[3]={'d','e','f'};
for(int i=0;i<3;i++)
{
EnQueue(q,b[i]);
}
QueueLength(q);
DispQueue(q);
ClearQueue(q);
return 0;
}