本节总结了栈和队列的基本概念和用法,另外附上栈与队列的基本操作代码(C语言版)。
本节适合有C语言基础的初学者、期末复习、考研等方面的用途。
#include "stdio.h"
#include "malloc.h"
#include "stdbool.h"
#define SElemType int
#define STACK_INIT_SIZE 10 //栈初始大小
#define STACK_INCREMENT 2 //栈递增大小
typedef struct SqStack {
SElemType *base; //在栈构造之前和销毁之后,base的值为NULL
SElemType *top; //栈顶指针
int stacksize; //当前已分配的存储空间,以元素为单位
}SqStack;
void InitStack(SqStack *S) { //构造一个空栈S
(*S).base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!(*S).base)
exit(1);
(*S).top=(*S).base;
(*S).stacksize=STACK_INIT_SIZE;
}
void DestroyStack(SqStack *S) { //销毁栈S,S不再存在
free((*S).base);
(*S).base=NULL;
(*S).top=NULL;
(*S).stacksize=0;
}
bool StackEmpty(SqStack S) { //若栈S为空栈,则返回TRUE,否则返回FALSE
if(S.top==S.base)
return true;
else
return false;
}
int StackLength(SqStack S) { //返回S的元素个数,即栈的长度
return S.top-S.base;
}
bool GetTop(SqStack S,SElemType *e) { //若栈不空,则用e返回S的栈顶元素,并返回TRUE;否则返回FALSE
if(S.top>S.base) {
*e=*(S.top-1);
return true;
}
else
return false;
}
void Push(SqStack *S,SElemType e) { //插入元素e为新的栈顶元素
if((*S).top-(*S).base>=(*S).stacksize) {
(*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACK_INCREMENT)*sizeof(SElemType));
if(!(*S).base)
exit(1);
(*S).top=(*S).base+(*S).stacksize;
(*S).stacksize+=STACK_INCREMENT;
}
*((*S).top)++=e;
}
bool Pop(SqStack *S,SElemType *e) { //若栈不空,则弹出S的栈顶元素,用e返回其值,并返回TRUE;否则返回FALSE
if((*S).top==(*S).base)
return false;
*e=*--(*S).top;
return true;
}
void StackTraverse(SqStack S,void(*visit)(SElemType)) { //从栈底到栈顶依次对栈中每个元素调用函数visit()
while(S.top>S.base)
visit(*S.base++);
printf("\n");
}
void PrintElement(SElemType e) { //visit函数
printf("%d ", e);
}
int main() {
//创建顺序栈并初始化
SqStack stack;
InitStack(&stack);
// 插入一些元素
Push(&stack, 1);
Push(&stack, 2);
Push(&stack, 3);
printf("Stack Length: %d\n", StackLength(stack));
// 依次打印这些元素
printf("Stack Elements: ");
StackTraverse(stack, PrintElement);
// 从栈顶依次取出元素
SElemType popped_element;
while (Pop(&stack, &popped_element)) {
printf("Popped Element: %d\n", popped_element);
}
printf("Stack Length: %d\n", StackLength(stack));
//销毁顺序栈
DestroyStack(&stack);
return 0;
}
#include
#include
#include
#define ElemType int
typedef struct Node { // 定义链表结点
ElemType data;
struct Node *next;
} Node;
typedef struct { // 定义链表栈结构
Node *top; // 栈顶指针
} LinkStack;
void InitStack(LinkStack *stack) { // 初始化链表栈
stack->top = NULL;
}
void DestroyStack(LinkStack *stack) { // 销毁链表栈
Node *p = stack->top;
while (p) {
Node *temp = p;
p = p->next;
free(temp);
}
stack->top = NULL;
}
bool StackEmpty(LinkStack stack) { // 判断栈是否为空
return stack.top == NULL;
}
bool GetTop(LinkStack stack, ElemType *e) { // 获取栈顶元素
if (StackEmpty(stack)) {
return false; // 栈为空,无法获取栈顶元素
}
*e = stack.top->data;
return true;
}
bool Push(LinkStack *stack, ElemType e) { // 入栈操作
Node *newNode = (Node *)malloc(sizeof(Node));
if (!newNode) {
printf("内存分配失败");
return false;
}
newNode->data = e;
newNode->next = stack->top;
stack->top = newNode;
return true;
}
bool Pop(LinkStack *stack, ElemType *e) { // 出栈操作
if (StackEmpty(*stack)) {
printf("空栈");
return false;
}
Node *temp = stack->top;
*e = temp->data;
stack->top = temp->next;
free(temp);
return true;
}
void ClearStack(LinkStack *stack) { // 清空栈
Node *p = stack->top;
while (p) {
Node *temp = p;
p = p->next;
free(temp);
}
stack->top = NULL;
}
int StackLength(LinkStack stack) { // 链表栈的长度
int length = 0;
Node *p = stack.top;
while (p) {
length++;
p = p->next;
}
return length;
}
bool GetElement(LinkStack stack, int index, ElemType *e) { // 根据索引获取栈中元素
if (index < 1 || index > StackLength(stack)) {
printf("非法索引值");
return false;
}
Node *p = stack.top;
for (int i = 1; i < index; i++) {
p = p->next;
}
*e = p->data;
return true;
}
bool ModifyElement(LinkStack *stack, int index, ElemType e) { // 修改栈中指定索引的元素
if (index < 1 || index > StackLength(*stack)) {
printf("非法索引值");
return false;
}
Node *p = stack->top;
for (int i = 1; i < index; i++) {
p = p->next;
}
p->data = e;
return true;
}
bool DeleteElement(LinkStack *stack, int index, ElemType *e) { // 删除栈中指定索引的元素
if (index < 1 || index > StackLength(*stack)) {
printf("非法索引值");
return false;
}
Node *p = stack->top;
if (index == 1) {
stack->top = p->next;
} else {
Node *pre = NULL;
for (int i = 1; i < index; i++) {
pre = p;
p = p->next;
}
pre->next = p->next;
}
*e = p->data;
free(p);
return true;
}
void PrintStack(LinkStack stack) { // 打印栈中元素
Node *p = stack.top;
printf("Stack Elements: ");
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
//初始化堆栈
LinkStack stack;
InitStack(&stack);
//向堆栈中存入数据
Push(&stack, 1);
Push(&stack, 2);
Push(&stack, 3);
printf("Stack Length: %d\n", StackLength(stack));
//打印堆栈
PrintStack(stack);
//获取栈顶数据
ElemType top_element;
if (GetTop(stack, &top_element)) {
printf("Top Element: %d\n", top_element);
}
//取出栈顶数据
ElemType popped_element;
if (Pop(&stack, &popped_element)) {
printf("Popped Element: %d\n", popped_element);
}
printf("Stack Length after popping: %d\n", StackLength(stack));
//调整堆栈的2号数据为5
ModifyElement(&stack, 2, 5);
PrintStack(stack);
//销毁堆栈
DestroyStack(&stack);
return 0;
}
#include
#include
#define MAX_SIZE 10 // 队列最大容量为10
typedef int ElemType;
typedef struct {
ElemType data[MAX_SIZE];
int front; // 队头指针
int rear; // 队尾指针
} CircularQueue;
// 初始化环状顺序队列
void InitQueue(CircularQueue *queue) {
queue->front = 0;
queue->rear = 0;
}
// 销毁环状顺序队列
void DestroyQueue(CircularQueue *queue) {
queue->front = 0;
queue->rear = 0;
}
// 判断队列是否为空
bool QueueEmpty(CircularQueue queue) {
return queue.front == queue.rear; //牺牲一个存储单元作为判空和判满的条件
}
// 判断队列是否已满
bool QueueFull(CircularQueue queue) {
return (queue.rear + 1) % MAX_SIZE == queue.front;
}
// 入队操作
bool EnQueue(CircularQueue *queue, ElemType e) {
if (QueueFull(*queue)) {
return false; // 队列已满,无法入队
}
queue->data[queue->rear] = e;
queue->rear = (queue->rear + 1) % MAX_SIZE; // 队尾指针后移
return true;
}
// 出队操作
bool DeQueue(CircularQueue *queue, ElemType *e) {
if (QueueEmpty(*queue)) {
return false; // 队列为空,无法出队
}
*e = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE; // 队头指针后移
return true;
}
// 获取队头元素
bool GetFront(CircularQueue queue, ElemType *e) {
if (QueueEmpty(queue)) {
return false; // 队列为空,无法获取队头元素
}
*e = queue.data[queue.front];
return true;
}
// 获取队尾元素
bool GetRear(CircularQueue queue, ElemType *e) {
if (QueueEmpty(queue)) {
return false; // 队列为空,无法获取队尾元素
}
*e = queue.data[(queue.rear - 1 + MAX_SIZE) % MAX_SIZE];
return true;
}
int main() {
//创建并初始化队列
CircularQueue queue;
InitQueue(&queue);
//添加元素
EnQueue(&queue, 1);
EnQueue(&queue, 2);
EnQueue(&queue, 3);
//获取队头元素
ElemType front_element, rear_element;
if (GetFront(queue, &front_element)) {
printf("Front Element: %d\n", front_element);
}
//获取队尾元素
if (GetRear(queue, &rear_element)) {
printf("Rear Element: %d\n", rear_element);
}
//出队操作
ElemType dequeued_element;
while (DeQueue(&queue, &dequeued_element)) {
printf("Dequeued Element: %d\n", dequeued_element);
}
//销毁队列
DestroyQueue(&queue);
return 0;
}
#include
#include
#include
#include
typedef struct { // 定义栈结构
char *data; // 栈数组指针
int top; // 栈顶指针
int maxSize; // 栈最大容量
} Stack;
void initStack(Stack *stack, int maxSize) { // 初始化栈
stack->data = (char *)malloc(maxSize * sizeof(char));
stack->top = -1;
stack->maxSize = maxSize;
}
void destroyStack(Stack *stack) { // 销毁栈
free(stack->data);
stack->data = NULL;
stack->top = -1;
stack->maxSize = 0;
}
bool isEmpty(Stack *stack) { // 判断栈是否为空
return stack->top == -1;
}
bool push(Stack *stack, char c) { // 入栈
if (stack->top == stack->maxSize - 1) {
return false; // 栈满,无法入栈
}
stack->data[++stack->top] = c;
return true;
}
bool pop(Stack *stack, char *c) { // 出栈
if (isEmpty(stack)) {
return false; // 栈空,无法出栈
}
*c = stack->data[stack->top--];
return true;
}
bool isValid(char *s) { // 括号匹配函数
Stack stack;
initStack(&stack, strlen(s)); // 初始化栈
int i = 0;
while (s[i] != '\0') {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
push(&stack, s[i]); // 左括号入栈
} else if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
char top;
if (pop(&stack, &top)) {
// 检查右括号是否匹配栈顶的左括号
if ((s[i] == ')' && top != '(') ||
(s[i] == ']' && top != '[') ||
(s[i] == '}' && top != '{')) {
destroyStack(&stack);
return false; // 括号不匹配
}
} else {
destroyStack(&stack);
return false; // 栈空,没有左括号与之匹配
}
}
i++;
}
bool result = isEmpty(&stack); // 判断栈是否为空
destroyStack(&stack); // 销毁栈
return result;
}
int main() {
char expr1[] = "{[()]}";
char expr2[] = "{[()]}[";
printf("表达式 1 : %s\n", isValid(expr1) ? "正确" : "错误");
printf("表达式 2 : %s\n", isValid(expr2) ? "正确" : "错误");
return 0;
}