数据结构 - 栈的实现(c语言)

目录

前言:

栈的实现方式讨论

栈的实现

栈的定义

接口函数

接口函数实现

1、初始化栈(StackInit)

2、销毁(StackDestroy)

3、入栈(StackPush)

4、出栈(StackPop)

5、返回栈顶数据(StackTop)

6、计算栈的大小(StackSize)

7、判断栈是否为空(StackIfEmpty)

完整代码:

Stack.h

Stack.c 

OJ练习:


前言:

  • 栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFOLast In First Out)原则。
  • 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶
  • 出栈:栈的删除操作叫做出栈。出数据也在栈顶

栈的实现方式讨论

实现栈无非就两种结构:数组结构 和 链式结构;

相对而言数组的结构实现更优,尾插尾删的效率高,缓存利用率高,它的唯一缺点只是增容,但是增容1次扩2倍对栈来说本身就比较合理,是无伤大雅的。而链式栈虽然不会空间浪费,用一个 malloc 申请一个,但是链式栈存在一个致命的缺点:单链表不好出数据,必须要实现双向链表,否则尾上删除数据将会异常麻烦。

总结:

栈的实现一般可以使用 数组或者链表实现 ,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。

栈的实现

栈的定义

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶的位置
	int capacity;	// 容量
}ST;

接口函数

void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
STDataType StackTop(ST* ps);

接口函数实现

1、初始化栈(StackInit)

void StackInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;    //个数
	ps->capacity = 0;    //容量
}

        初始化和顺序表几乎没有什么区别。首先通过结构体指针(我们定义的Stack) ps 指向 array,将数组为空。因为是初始化,所以将有效数据个数和数组时即能存数据的空间容量一并置为0。

2、销毁(StackDestroy)

void StackDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

首先把栈 free 掉,为了防止野指针我们手动把它置为空指针(好习惯)

3、入栈(StackPush)

void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	// 
	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		ps->a = (STDataType*)realloc(ps->a, newCapacity* sizeof(STDataType));
		if (ps->a == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}

		ps->capacity = newCapacity;
	}

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

4、出栈(StackPop)

void StackPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--ps->top;
}

5、返回栈顶数据(StackTop)

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}

6、计算栈的大小(StackSize)

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

7、判断栈是否为空(StackIfEmpty)

bool StackEmpty(ST* ps)
{
	assert(ps);

	/*if (ps->top > 0)
	{
		return false;
	}
	else
	{
		return true;
	}*/
	return ps->top == 0;
}

完整代码:

Stack.h

#pragma once

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

//struct Stack
//{
//	int a[N];
//	int top; // 栈顶的位置
//};

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶的位置
	int capacity;	// 容量
}ST;

void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
STDataType StackTop(ST* ps);

Stack.c 

#include "Stack.h"

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

void StackDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	// 
	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		ps->a = (STDataType*)realloc(ps->a, newCapacity* sizeof(STDataType));
		if (ps->a == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}

		ps->capacity = newCapacity;
	}

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

void StackPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--ps->top;
}

bool StackEmpty(ST* ps)
{
	assert(ps);

	/*if (ps->top > 0)
	{
		return false;
	}
	else
	{
		return true;
	}*/
	return ps->top == 0;
}

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}


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

OJ练习:

20. 有效的括号 - 力扣(LeetCode)

为了演示代码,我这边直接复制粘贴上文,有许多代码是“没用的”,所以看起来非常长

思路:

首先将所给的字符串进行遍历,如果是左括号就将它压入栈中,根据栈后进先出的特性,然后逐个取出栈中的左括号与后面剩下的右括号进行逐对进行匹配,如果不匹配就返回false,如果都匹配了就返回true。

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶的位置
	int capacity;	// 容量
}ST;

void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
STDataType StackTop(ST* ps);

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

void StackDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	// 
	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		ps->a = (STDataType*)realloc(ps->a, newCapacity* sizeof(STDataType));
		if (ps->a == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}

		ps->capacity = newCapacity;
	}

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

void StackPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--ps->top;
}

bool StackEmpty(ST* ps)
{
	assert(ps);

	/*if (ps->top > 0)
	{
		return false;
	}
	else
	{
		return true;
	}*/
	return ps->top == 0;
}

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}


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

//表演开始了
bool isValid(char * s){
    ST st;
    StackInit(&st);

    while(*s)
    {
        if(*s=='['||*s=='('||*s=='{')
        {
            StackPush(&st,*s);
            s++;
        }
        else
        {
            if(StackEmpty(&st))
                return false;

            char top=StackTop(&st);
            StackPop(&st);

            if(*s==']'&&top!='['
            ||*s==')'&&top!='('
            ||*s=='}'&&top!='{')
            {
                StackDestory(&st);
                return false;
            }
            else
            {
                s++;
            }
        }
    }

    bool ret=StackEmpty(&st);   //  栈为空声明所以左括号匹配
    StackDestory(&st);
    return ret;


}

简化


    解题思路:
     该题比较简单,是对栈特性很好的应用,具体操作如下:
     循环遍历String中的字符,逐个取到每个括号,如果该括号是:
        1. 左括号,直接入栈
        2. 右括号,与栈顶的左括号进行匹配,如果不匹配直接返回false
           否则继续循环
     循环结束后,如果栈空则匹配,否则左括号比右括号多肯定不匹配


class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<>();
        for(int i = 0; i < s.length(); ++i){
            char ch = s.charAt(i);
            // 如果是左括号则入栈
            if('(' == ch || '[' == ch || '{' == ch){
                st.push(ch);
            }else{
                // ch为右括号
                // 此时应该到栈顶检测,是否和对应的左括号匹配
                // 注意:要检测必须要保证栈中有元素
                if(st.isEmpty()){
                    return false;
                }
 
                char left = st.pop();
                // 如果ch表示右括号与栈顶左括号不匹配时直接返回
                if(!(('(' == left && ')' == ch) ||
                   ('[' == left && ']' == ch) ||
                   ('{' == left && '}' == ch))){
                       return false;
                   }
 
                // ch表示的右括号 和 left表示的栈顶左括号匹配
                // 继续循环检测
            }
        }
        // 左括号比右括号多,也不匹配
        if(!st.isEmpty()){
            return false;
        }
        return true;
    }
}

 C++写法

思路:将所有左括号入栈,利用后进先出性质匹配右括号

class Solution {
public:
    bool isValid(string s) {

        unordered_map<char, char> pairs = {
            {')', '('},
            {']', '['},
            {'}', '{'}
        };
        stack<char> stk;
        for (char ch: s) {
            if (pairs.count(ch)) 
            {
                if (stk.empty() || stk.top() != pairs[ch]) {
                    return false;
                }
                stk.pop();
            }
            else {
                stk.push(ch);
            }
        }
        return stk.empty();
    }
};

  • 16
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

NO.-LL

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

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

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

打赏作者

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

抵扣说明:

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

余额充值