顺序栈、顺序队列为树相关的操作打下基础
一、顺序栈
//顺序栈的操作
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define STACK_SIZE 5
//typedef int ElemType;
typedef struct {
int top;
int data[STACK_SIZE];//这是一个数组
}SqStack,*Stack;
//初始化
void InitStack(Stack s){
s->top=-1;
}
//判断栈是否为空
int StackEmpty(Stack s){
if(s->top==-1)
return 0;
else
return 1;
}
//将数据x进栈
int push(Stack s,int x){
if(s->top==STACK_SIZE-1)
return 0;
s->top++;
s->data[s->top]=x;
return 1;
}
//将栈顶元素出栈
int pop(Stack s){
if(s->top!=-1){
return s->data[s->top--];
}
}
//读栈顶元素
int GetTop(Stack s){
if(s->top==-1)
return 0;
return s->data[s->top];
}
int main(){
Stack s;
int num,i;
s=(Stack)malloc(sizeof(SqStack));
InitStack(s);
while(scanf("%d",&num),num!=0){
i=push(s,num);
if(i<=0){
printf("栈已经满了,停止输入\n");
break;
}
}
while(StackEmpty(s)){
printf("top的值为%d 栈顶元素为%d \n",s->top,GetTop(s));
printf("将%d出栈\n",pop(s));
}
return 0;
}
二、顺序队列
//队列的操作
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
//顺序存储结构定义
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];
int top;
int rear;
}SqQueue,*SQ;
//初始化
void Init(SQ Q){
Q->top=-1;
Q->rear=-1;
}
//入队列,队列的尾元素下标先加一再入元素
int EnQueue(SQ Q,ElemType x){
if(Q->rear==MAXSIZE-1){//判断是否已经“满”(尽管是假溢出,但还是要考虑这种)
return 0;
}
else{
Q->data[++Q->rear]=x;
return 1;
}
}
//出队列
int DeQueue(SQ Q){
if(Q->rear-Q->top==0){//队列为空
return 0;
}
else
return Q->data[++Q->top];
}
int main(){
SQ q;
int num;
q=(SQ)malloc(sizeof(SqQueue));
Init(q);
while(scanf("%d",&num),num!=-1){
EnQueue(q,num);
}
//printf("队尾元素的下标为:%d\n",q->rear);
while(q->rear!=q->top){
printf("将%d出队列\n",DeQueue(q));
}
return 0;
}
三、链式队列
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LinkNode;
typedef struct Queue{
LinkNode *front,*rear;
}LinkQueue,*LQueue;
//初始化,带头结点的链式队列
void InitQueue(LQueue Q){
Q->front=Q->rear=(LinkNode *)malloc(sizeof(LinkNode));
Q->front->next=NULL;
}
//判断队空
int IsEmpty(LQueue Q){
if(Q->front==Q->rear)
return 1;
else
return 0;
}
//入队列
void EnQueue(LQueue Q,ElemType x){
LinkNode *s=(LinkNode*)malloc(sizeof(LinkNode));
s->data=x;
s->next=NULL;
Q->rear->next=s;
Q->rear=s;
}
//出队列
int DeQueue(LQueue Q,ElemType x){
LinkNode *p;
//如果队列为空
if(Q->front==Q->rear)
return 0;
p=Q->front->next;//出队为第一个结点元素,为Q->front->next
x=p->data;
Q->front->next=p->next;
if(Q->rear==p)
Q->rear=Q->front;
free(p);
return 1;
}
int main(){
int num,*x;
LQueue q;
q=(LQueue)malloc(sizeof(LinkQueue));
InitQueue(q);
//以0作为队列元素输入的结束
while(scanf("%d",&num),num!=0){
EnQueue(q,num);
}
printf("队列元素为:");
while(q->front!=q->rear){
printf("%d ",q->front->next->data);
DeQueue(q,x);
}
printf("\n");
return 0;
}