一、顺序栈
1、顺序栈的存储
#define Stacksize 100
typedef int Datatype;
typedef struct
{
Datatype data[Stacksize];
int top;//栈顶元素在数组中的下标
}Seqstack;
2、顺序栈的实现
初始化
把top设置为-1
入栈
int Push(SeqStack *S, DataType x)
{
if (S->top —-StackSize- 1){
printf("上溢错误,插入失败\n"); return 0;}
s->data[++S->top] return 1:
}
出栈
int Pop(SeqStack *S, DataType*ptr){//ptr提取元素
if (S->top==-1){
printf("下溢错误,删除失败n");(return 0;}
*ptr=S->data(S->[top--]) return 1;
}
取值
与出栈类似,top不自减
判空
int Empty(SeqStack *S)
{
if(S->top==return1) return 1;
else return 0;
}
二、链栈
1、链栈的存储
typedef int DataType;
/*栈元素的数据类型,假设为int型*/
typedef struct Node
{
DataType data;
/*存放栈元素的数据域*/
struct Node *next;
/*存放下一个结点的地址*/
}Node;
Node *top;
2、链栈的实现
入栈
void Push(Node*(top, DataType{//不用进行判断,链表不会上溢
Node *s = (Node *)malloc(sizeof(Node));
s->data= X;
s->next = top->next;
top->next=s;
}
出栈
int Pop(Node *top, DataType *ptr)
{
Node *p = top;if (top =- NULL){
printf("下溢错误,删除失败\n"); return 0;}
*ptr = top->data;
top = top->next; free(p);return l;
}
销毁
void DestroyStack(Node *top){
Node *p=top;
while (top !=NULL){
top = top->next;free(p) p=top}
}
三、循环队列
存储结构定义
#define QueueSize 100
/产*定义数组的最大长度*/
typedef int DataType;
/*队列元素的数据类型,假设为int型*/
typedef struct
{
DataType data[QueueSize];
/*存放队列元素的数组*/
int front,rear;
/*下标,队头元素和队尾元素的位置*/
}CirQueue;
初始化
void InitQueue(CirQueue *Q)
{
Q->front = Q->rear = QueueSize- 1;
}
判空操作
int Empty(CirQueue *Q){
if(Q->rear == Q->front) return 1;
else return 0;
}
插入操作
int EnQueue(CirQueue *Q, DataType x)
{
if ((Q->rear+1) % QueueSize =- Q->front){
printf(上溢错误,插入失败\n"); return 0;
}
Q->rear = (Q->rear + 1)%QueueSize;
Q->data[Q->rear]=x;
return 1;
}
删除操作
int DeQueue(CirQueue *Q, DataType*ptr){
if(Q->rear== Q->front){
printf(“下溢错误,删除失败\n"); return 0;
}
Q->front =(Q->front+1) % QueueSize;
*ptr = Q->data[Q->front];
return 1;
}
四、链队
存储
typedef int DataType; /*定义队列元素的数据类型,假设为int型*/
typedef struct Node /*定义链队列的结点结构*/
{
DataType data;struct Node *next;}
Node;
typedef struct /*定义链队列*/
{
Node *front,*rear;}
LinkQueue;
入队
void EnQueue(LinkQueue *Q,DataType x)
{
Node *s = (Node * )malloc(sizeof(Node));
s->data= x; s->next = NULL;
Q->rear->next =s; Q->rear = s;
}
出队
int DeQueue(LinkQueue *Q,DataType*ptr){
Node *p;
if(Q->rear ==Q->front){
printf("下溢错误,删除失败\n"); returO;
}
p =Q->front->next;*ptr =p->data;
Q->front->next =p->next;
if(p->next =- NULL)Q->rear =Q->front;
free(p);
return 1;
销毁
void DestroyQueue(LinkQueue *Q)
{
Node *p=Q->front;
while (p !=NULL){
Q->front =p->next;free(p);
p=Q>front;}
}