C语言编写一个程序实现顺序栈的各种基本运算,实现队列的链式表示和实现。
时间: 2023-11-22 17:55:47 浏览: 98
顺序栈的基本运算:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} SqStack;
void initStack(SqStack *s) {
s->top = -1;
}
int isEmpty(SqStack *s) {
return s->top == -1;
}
int isFull(SqStack *s) {
return s->top == MAX_SIZE - 1;
}
void push(SqStack *s, int x) {
if (isFull(s)) {
printf("Error: stack is full.\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(SqStack *s) {
if (isEmpty(s)) {
printf("Error: stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int top(SqStack *s) {
if (isEmpty(s)) {
printf("Error: stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
int main() {
SqStack s;
initStack(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("%d\n", pop(&s));
printf("%d\n", top(&s));
printf("%d\n", pop(&s));
printf("%d\n", pop(&s));
printf("%d\n", isEmpty(&s));
return 0;
}
```
队列的链式表示和实现:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *QueuePtr;
typedef struct {
QueuePtr front; // 头指针
QueuePtr rear; // 尾指针
} LinkQueue;
void initQueue(LinkQueue *q) {
q->front = q->rear = (QueuePtr) malloc(sizeof(Node));
if (!q->front) {
printf("Error: failed to allocate memory.\n");
exit(1);
}
q->front->next = NULL;
}
int isEmpty(LinkQueue *q) {
return q->front == q->rear;
}
void enQueue(LinkQueue *q, int x) {
QueuePtr p = (QueuePtr) malloc(sizeof(Node));
if (!p) {
printf("Error: failed to allocate memory.\n");
exit(1);
}
p->data = x;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
int deQueue(LinkQueue *q) {
if (isEmpty(q)) {
printf("Error: queue is empty.\n");
exit(1);
}
QueuePtr p = q->front->next;
int x = p->data;
q->front->next = p->next;
if (q->rear == p) {
q->rear = q->front;
}
free(p);
return x;
}
int main() {
LinkQueue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printf("%d\n", deQueue(&q));
printf("%d\n", deQueue(&q));
printf("%d\n", deQueue(&q));
printf("%d\n", isEmpty(&q));
return 0;
}
```
阅读全文