建立一个顺序栈,建立一个循环顺序队列,分别实现栈和队列的基本操作。用c语言
时间: 2023-06-14 09:04:12 浏览: 104
以下是基本操作的实现代码:
顺序栈:
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} SeqStack;
void InitStack(SeqStack *S) {
S->top = -1;
}
int IsEmpty(SeqStack S) {
if (S.top == -1)
return 1;
else
return 0;
}
int IsFull(SeqStack S) {
if (S.top == MAXSIZE - 1)
return 1;
else
return 0;
}
void Push(SeqStack *S, int x) {
if (IsFull(*S))
printf("Stack is full.\n");
else {
S->top++;
S->data[S->top] = x;
}
}
int Pop(SeqStack *S) {
if (IsEmpty(*S)) {
printf("Stack is empty.\n");
return -1;
} else {
int x = S->data[S->top];
S->top--;
return x;
}
}
int GetTop(SeqStack S) {
if (IsEmpty(S)) {
printf("Stack is empty.\n");
return -1;
} else {
return S.data[S.top];
}
}
```
循环顺序队列:
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int front, rear;
} SeqQueue;
void InitQueue(SeqQueue *Q) {
Q->front = 0;
Q->rear = 0;
}
int IsEmpty(SeqQueue Q) {
if (Q.front == Q.rear)
return 1;
else
return 0;
}
int IsFull(SeqQueue Q) {
if ((Q.rear + 1) % MAXSIZE == Q.front)
return 1;
else
return 0;
}
void EnQueue(SeqQueue *Q, int x) {
if (IsFull(*Q))
printf("Queue is full.\n");
else {
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAXSIZE;
}
}
int DeQueue(SeqQueue *Q) {
if (IsEmpty(*Q)) {
printf("Queue is empty.\n");
return -1;
} else {
int x = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return x;
}
}
int GetFront(SeqQueue Q) {
if (IsEmpty(Q)) {
printf("Queue is empty.\n");
return -1;
} else {
return Q.data[Q.front];
}
}
```
阅读全文