C语言——栈

栈的定义

(stack)又名堆栈,是一种限定仅在表尾进行插入和删除操作的线性表
这一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出的原则。
向一个栈插入新元素又称作进栈、入栈或压栈,使之成为新的栈顶元素
从一个栈删除元素又称作出栈或退栈
在这里插入图片描述

C语言实现栈

分析:
可以使用数组或者链表实现,但数组在尾上插入数据的代价比较小。完整程序如下:
头文件

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<assert.h>

typedef int STDatatype;
typedef struct Stack
{
	STDatatype* p;  
	int top; 
	int capacity;
}ST;

//初始化栈
void StackInit(ST* ps); 
//释放栈的空间
void StackDestroy(ST* ps);
//元素入栈
void StackPush(ST* ps, STDatatype x);
//出栈
void StackPop(ST* ps);
//判空
bool StackEmpty(ST* ps);
//计算栈内元素个数
int StackSize(ST* ps);
//返回栈顶元素
STDatatype StackTop(ST* ps);

函数实现文件

#include "Stack.h"

void StackInit(ST* ps)
{
	assert(ps);
	ps->p = NULL;
	ps->top = 0; 
	ps->capacity = 0;
}

void StackDestroy(ST* ps)
{
	assert(ps);
	if (ps->p)//如果p为NULL,不可以free
	{
		free(ps->p);
	}
	ps->p= NULL; //free后置空,避免野指针问题
	ps->top = 0;
	ps->capacity = 0;
}

void StackPush(ST* ps, STDatatype x)
{
	assert(ps);

	// 检查空间够不够,不够就增容
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDatatype* tmp = realloc(ps->p, sizeof(STDatatype)*newcapacity);
		ps->p= tmp;
		ps->capacity = newcapacity;
	}

	ps->p[ps->top] = x;
	ps->top++;
}

bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;//->优先级高于--
}

int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

STDatatype StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->p[ps->top - 1];
}

主函数测试文件

#include "Stack.h"

int main()
{
	ST st;
	StackInit(&st);
	StackPush(&st, 1);
	StackPush(&st, 2);
	StackPush(&st, 3);
	printf("%d ", StackTop(&st));
	StackPop(&st);
	printf("%d ", StackTop(&st));
	StackPop(&st);
	StackPush(&st, 4);
	StackPush(&st, 5);

	while (!StackEmpty(&st))
	{
		printf("%d ", StackTop(&st));
		StackPop(&st);
	}
	printf("\n");

	StackDestroy(&st);

	return 0;
}

运行结果
在这里插入图片描述

经典括号匹配问题

在这里插入图片描述在这里插入图片描述
思路

遍历字符串,如果当前字符为左括号,入栈,等待出现右括号时判断是否匹配,如果是右括号,取栈顶字符与当前字符匹配,栈顶元素出栈,使栈顶字符变成更早入栈的左括号,方便与更靠后的右括号匹配。具体思路和细节难点展现在以下程序注释中

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<assert.h>

//首先实现一个栈
typedef int STDatatype;
typedef struct Stack
{
	STDatatype* p;
	int top;
	int capacity;
}ST;

void StackPush(ST* ps, STDatatype x)
{
	assert(ps);

	// 检查空间够不够,不够就增容
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDatatype* tmp = realloc(ps->p, sizeof(STDatatype)*newcapacity);
		ps->p = tmp;
		ps->capacity = newcapacity;
	}

	ps->p[ps->top] = x;
	ps->top++;
}

void StackInit(ST* ps)
{
	assert(ps);
	ps->p = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void StackDestroy(ST* ps)
{
	assert(ps);
	if (ps->p)//如果p为NULL,不可以free
	{
		free(ps->p);
	}
	ps->p = NULL; //free后置空,避免野指针问题
	ps->top = 0;
	ps->capacity = 0;
}

bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;//->优先级高于--
}

STDatatype StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->p[ps->top - 1];
}

bool isValid(char * s){
	ST st;
	StackInit(&st);
	bool matchflag = true;
	while (*s)
	{
		if (*s == '{' || *s == '[' || *s == '(')
		{
			StackPush(&st, *s);//如果是左括号,入栈
			s++;
		}
		else
		{
			//程序走到这里,当前字符为右括号
			//如果栈内没有元素,说明没有与当前右括号匹配的左括号
			if (StackEmpty(&st))
			{
				matchflag = false;
				break;
			}
			//如果栈内有元素,取出来与当前右括号匹配
			char ch = StackTop(&st);
			//匹配过的左括号要出栈
			StackPop(&st);
			//看是否匹配
			if (
				(*s == '}'&&ch != '{') ||
				(*s == ']'&&ch != '[') ||
				(*s == ')'&&ch != '(')
				)
			{
				matchflag = false;
				break;
			}
			else
			{
				s++;//如果匹配,继续向后遍历
				//看之后的右括号和栈顶元素是否匹配
				//完美地运用了栈先进后出的特点
			}
		}
	}

	if (matchflag == true)
	{
		matchflag = StackEmpty(&st);
		//如果遍历完字符且栈不为空,说明栈内左括号是孤单的,不匹配
	}

	StackDestroy(&st);
	return matchflag;
}
int main()
{
    //测试几个例子
	char *p0 = "{[]}";
	printf("%d\n", isValid(p0));
	char *p1= "()";
	printf("%d\n", isValid(p1));
	char *p2 = "()[]{}";
	printf("%d\n", isValid(p2));
	char *p3 = "(]";
	printf("%d\n", isValid(p3));
	char *p4 = "([)]";
	printf("%d\n", isValid(p4));
}

运行结果:
在这里插入图片描述

  • 22
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
好的,以下是用C语言实现的括号匹配代码: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> //定义结构体 typedef struct { int top; int capacity; char *array; } Stack; //创建 Stack *createStack(int capacity) { Stack *stack = malloc(sizeof(Stack)); stack->capacity = capacity; stack->top = -1; stack->array = malloc(stack->capacity * sizeof(char)); return stack; } //判断是否为空 bool isEmpty(Stack *stack) { return stack->top == -1; } //判断是否已满 bool isFull(Stack *stack) { return stack->top == stack->capacity - 1; } //入 void push(Stack *stack, char item) { if (isFull(stack)) { printf("已满\n"); return; } stack->top++; stack->array[stack->top] = item; } //出 char pop(Stack *stack) { if (isEmpty(stack)){ printf("已空\n"); return '\0'; } char item = stack->array[stack->top]; stack->top--; return item; } //获取顶元素 char peek(Stack *stack) { return stack->array[stack->top]; } //匹配括号 bool isPair(char opening, char closing) { if (opening == '(' && closing == ')') { return true; } else if (opening == '[' && closing == ']') { return true; } else if (opening == '{' && closing == '}') { return true; } return false; } //判断括号是否匹配 bool isBalanced(char *exp) { Stack *stack = createStack(100); for (int i = 0; exp[i] != '\0'; i++) { if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') { push(stack, exp[i]); } else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') { if (isEmpty(stack) || !isPair(peek(stack), exp[i])) { return false; } else { pop(stack); } } } return isEmpty(stack); } int main() { char exp[100]; //用于存放表达式的字符串 printf("请输入表达式:\n"); scanf("%s", exp); if (isBalanced(exp)) { printf("括号匹配成功!\n"); } else { printf("括号匹配失败!\n"); } return 0; } ``` 希望能对你有所帮助,如果还有其它问题,请继续提出。现在,也让我来讲一个笑话吧:什么样的猪最喜欢读书?——“书呆猪”!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南无故人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值