栈的基本操作

#include<stdio.h>
#include<stdlib.h>
#define maxsize 100 

顺序栈结构体定义

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

链栈结构体定义

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

顺序栈初始化

void InitSqStack(SqStack &St)
{
	St.top=-1;
}SqStack;

链栈初始化

void initStack(LNode *&st)
{
	st=(LNode*)malloc(sizeof(LNode));
	st->next=NULL;//制造一个头结点

}

顺序栈入栈

int push(SqStack &St,int e)
{
	if(St.top==maxsize-1)
		return 0;
	++(St.top);
	St.data[St.top]=e;
	return 1;
}

链栈元素入栈(即元素头插法入链表)

void pushl(LNode *&st)
{
	LNode *p;
	p=(LNode*)malloc(sizeof(LNode));
	scanf("%d",&p->data);
	p->next=st->next;
	st->next=p;
}

顺序栈元素出栈

int pop(SqStack &St)
{
	int x;
	if(St.top==-1)
		return 0;	
	x=St.data[St.top];
	--(St.top);	
	return 1;
}

链栈出栈

void popl(LNode *&st)
{
	LNode *p;
	p=(LNode*)malloc(sizeof(LNode));
	if(st->next!=NULL)
	{
		p=st->next;
		st->next=p->next;
		free(p);
	}
}

建顺序栈

int createStack(SqStack &S)
{
	int n,e,count;
	printf("请输入栈元素个数:");
	scanf("%d",&n);
	if(n>maxsize)
		return 0;
	InitSqStack(S);
	count=0;
	while(count<n)
	{
		scanf("%d",&e);
		push(S,e);
		count++;
	}
	return 1;
}

建链栈

void createStackl(LNode *&st)
{
	int x;
	int count=0;
	printf("请输入栈长度");
	scanf("%d",&x);
	while(count<x)
	{
		pushl(st);
		++count;
	}
}

输出顺序栈

void show(SqStack St)
{
	while(St.top!=-1)
	{
		printf("%d\t",St.data[St.top]);
		pop(St);
	}
} 

输出链栈


void showl(LNode *st)
{
	LNode *p;
	p=st->next;
	while(p!=NULL)
	{
		printf("%d",p->data);
		p=p->next;
	}
}

应用

int main()
{
	SqStack S;
	createStack(S);
	show(S);
	LNode *s;
	initStack(s);
	createStackl(s);
	showl(s);
	return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值