实验内容
1.采用顺序存储实现栈的初始化、入栈、出栈操作。
2.采用顺序存储实现循环队列的初始化、入队、出队操作。
代码实现
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100
//1.采用顺序存储实现栈的初始化、入栈、出栈操作。
//2.采用顺序存储实现循环队列的初始化、入队、出队操作。
//3.采用链式存储实现栈的初始化、入栈、出栈操作。
//4.采用链式存储实现队列的初始化、入队、出队操作。
/**********************************************************/
//顺序存储栈
typedef struct {
int val[MAX];
int top;
}Stack;
void init_stack(Stack* s) {
s->top = -1;
}
void push_stack(Stack* s) {
printf("Push Stack:\n");
if (s->top == MAX) {
printf("The Stack is Full!\n");
return;
}
printf("请输入要入栈的整数(-1结束): ");
int a = 1;
scanf("%d", &a);
while(a!=-1&&s->top!=MAX){
s->top++;
s->val[s->top] = a;
scanf("%d", &a);
}
}
void pop_stack(Stack* s) {
printf("Pop Stack:\n");
if (s->top == -1) {
printf("The Stack is Empty!\n");
return;
}
while (s->top != -1) {
printf("%d ", s->val[s->top]);
s->top--;
}
printf("\n\n");
}
void test_stack() {
Stack s;
init_stack(&s);
push_stack(&s);
pop_stack(&s);
}
/******************************************************************/
//顺序存储队列
typedef struct {
int val[MAX+1];
int front; //头
int rear; //尾
}Queue;
void init_queue(Queue* q) {
q->front = 0;
q->rear = 0;
}
void enqueue(Queue* q) {
printf("Enqueue:\n");
if ((q->rear + 1) % MAX == q->front) {
printf("The Queue is Full!\n");
return;
}
printf("请输入要入队的整数(-1结束): ");
int a = 1;
scanf("%d", &a);
while (a != -1&&((q->rear + 1) % MAX != q->front)) {
q->val[q->rear] = a;
q->rear = (q->rear + 1) % MAX;
scanf("%d", &a);
}
}
void dequeue(Queue* q) {
printf("Dequeue:\n");
if (q->front == q->rear) {
printf("The Queue is Empty!\n");
return;
}
while (q->front != q->rear) {
printf("%d ", q->val[q->front]);
q->front = (q->front + 1) % MAX;
}
printf("\n\n");
}
void test_queue() {
Queue q;
init_queue(&q);
enqueue(&q);
dequeue(&q);
}
int main() {
test_stack();
test_queue();
return 0;
}