栈,顺序栈,链栈

本文详细介绍了栈这种限定性线性表的基本概念、特点及其两种主要的存储结构:顺序存储结构和链式存储结构。通过具体的代码示例展示了如何实现栈的基本操作如初始化、进栈、出栈等。

        栈作为一种限定性线性表,是将表的插入删除限制为仅在表的一端进行,通常将表中允许插入删除的一端叫做栈顶(top),因此栈顶的当前位置是动态变化的。栈的另一端叫做栈底(bottom)。当栈中没有元素时称为空栈。插入操作称为进栈或入栈,删除操作称为出栈或退栈。栈是先进后出的线性表,简称为LIFO表。
        栈主要有两种基本的存储结构:顺序存储结构和链式存储结构。简称顺序存储的栈为顺序栈,链式存储的栈为链栈。

顺序栈

    存储结构

#define Stack_Size 50
typedef struct{
	StackElementType elem[Stack_Size];
	int top; 
}SeqStack;

        1.初始化

void InitStack(SeqStack *S) {
	S->top = -1;
}

        2.进栈

int Push(SeqStack *S, StackElementType x) {
	if(S->top == Stack_Size-1)
	    return FALSE;
	S->top++;
	S->elem[S->top] = x;
	return TRUE; 	
}

        3.出栈

int Pop(SeqStack *S, StackElementType *x){
	if(S->top == -1)
		return FALSE;
	else {
		*x = S->elem[S->top];
		S->top--;
		return TRUE; 
	}
}

        3.读栈顶元素

int GetTop(SeqStack *S, StackElementType *x){
	if(S->top == -1)
		return FALSE;
	else {
		*x = S->elem[S->top];
		return TRUE; 
	}
}

链栈

    存储结构

typedef struct node{
	StackElementType data;
	struct node *next; 
}LinkStackNode;
typedef LinkStackNode *LinkStack; 

        1.初始化

void InitStack(LinkStack *S) {
	S->next = NULL;
}

        2.进栈

int Push(LinkStack top, StackElementType x) {
	LinkStackNode *temp;
	temp = (LinkSatckNode*)malloc(sizeof(LinkStackNode));
	if(temp == NULL)
		return FALSE;
	temp->data = x;
	temp->next = top->next;
	top->next = temp;
	return TRUE; 	
}

        3.出栈

int Pop(LinkStack top, StackElementType *x){
	LinkStackNode *temp;
	temp = top->next;
	if(temp == NULL)
		return FALSE;
	top->next = temp->next;
	*x = temp->data;
	free(temp);
	return TRUE; 
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱吃鱼的ねこ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值