[C/C++]C语言之栈(Stack)

概述

栈(stack)是限定仅在表尾进行插入或删除操作的线性表。因此,对栈来说,表尾称为栈顶(top),表头端称为栈底(bottom),没有元素则称之为空栈。栈又称之为后进先出(last in first out)的线性表(LIFO)。

                                    


1、顺序栈

                                  

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

#define maxsize 100
typedef struct SqStack
{
    int data[maxsize];
    int top;
}SqStack;

//初始化顺序栈
void InitSqStack(SqStack *st)
{
    st->top=-1;
}

//判断栈是否为空
int IsEmpty(SqStack *st)
{
    return (st->top==-1?1:0);
}

//进栈
int Push(SqStack *st,int x)
{
    if(st->top==maxsize-1)
    {
        return 0;
    }
    st->data[++st->top]=x;
    return 1;
}

//出栈
int Pop(SqStack *st,int *x)
{
    if(st->top ==-1)
    {
        return 0;
    }
    *x=st->data[st->top--];
    return 1;
}

//打印栈元素
void PrintStack(SqStack *st)
{
    while(st->top !=-1)
    {
        printf("栈元素:%d\n",st->data[st->top--]);
    }
}

2、链栈

   链栈示意图

                                                        

    基本操作算法

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

typedef struct Lnode{
	int data;
	struct Lnode *next;
}Lnode;

//初始化链栈
void InitStack(Lnode *ln)
{
	ln=(Lnode *)malloc(sizeof(Lnode));
	ln->next=NULL;
}

//判断链栈是否为空
int IsEmpty(Lnode *ln)
{
	return (ln->next==NULL?1:0);
}

//进栈
void Push(Lnode *ln,int x)
{
	Lnode *p;
	p=(Lnode *)malloc(sizeof(Lnode));
	if(p ==NULL){
		printf("ERROR");
		exit(0);
	}
	p->next=NULL;
	p->data=x;
	p->next=ln->next;
	ln->next=p;
}

//出栈
int Pop(Lnode *ln,int *x)
{
	Lnode *p=ln->next;
	if(p ==NULL)
    {
		return 0;
	}
	*x=p->data;
	ln->next=p->next;
	free(p);
	return 1;
}

void PrintStack(Lnode *ln)
{
	Lnode *p=ln->next;
	while(p!=NULL)
    {
		printf("%d\n",p->data);
		p=p->next;
	}
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值