C语言程序代码列表,堆栈,队列
时间: 2023-05-28 17:06:55 浏览: 116
Go语言的队列和堆栈实现方法
1. 堆栈
定义堆栈结构体:
```
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
```
初始化堆栈:
```
void InitStack(Stack *s) {
s->top = -1;
}
```
判断堆栈是否为空:
```
int IsEmpty(Stack s) {
return s.top == -1;
}
```
判断堆栈是否已满:
```
int IsFull(Stack s) {
return s.top == MAXSIZE - 1;
}
```
入栈操作:
```
int Push(Stack *s, int x) {
if (IsFull(*s)) {
return 0;
}
s->data[++s->top] = x;
return 1;
}
```
出栈操作:
```
int Pop(Stack *s, int *x) {
if (IsEmpty(*s)) {
return 0;
}
*x = s->data[s->top--];
return 1;
}
```
获取栈顶元素:
```
int GetTop(Stack s, int *x) {
if (IsEmpty(s)) {
return 0;
}
*x = s.data[s.top];
return 1;
}
```
2. 队列
定义队列结构体:
```
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int front;
int rear;
} Queue;
```
初始化队列:
```
void InitQueue(Queue *q) {
q->front = q->rear = 0;
}
```
判断队列是否为空:
```
int IsEmpty(Queue q) {
return q.front == q.rear;
}
```
判断队列是否已满:
```
int IsFull(Queue q) {
return (q.rear + 1) % MAXSIZE == q.front;
}
```
入队操作:
```
int EnQueue(Queue *q, int x) {
if (IsFull(*q)) {
return 0;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE;
return 1;
}
```
出队操作:
```
int DeQueue(Queue *q, int *x) {
if (IsEmpty(*q)) {
return 0;
}
*x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return 1;
}
```
获取队头元素:
```
int GetFront(Queue q, int *x) {
if (IsEmpty(q)) {
return 0;
}
*x = q.data[q.front];
return 1;
}
```
阅读全文