顺序栈和链式栈的结构及其基本操作(置空,获取栈顶元素,入栈,出栈)

栈:仅在表尾进行插入和删除操作的线性表。

顺序栈

栈顶(top):允许插入和删除的一端。
栈底(bottom):另一端
空栈:top = -1
栈的特点:先进后出,后进先出(LIFO)结构

实例:

#include <stdio.h>

#define  OK    1
#define  ERROR 0
#define  MAX   10

typedef int StackData;
typedef struct stack
{
	StackData data[MAX];
	int top;
}Stack;

//创建栈
int Initstack(Stack *s)
{
	if(NULL == s)
		return ERROR;
	
	s->top = -1;
	return OK;
}

//入栈
int push(Stack *s, StackData data)
{
	if(s == NULL || s->top == MAX-1)
		return ERROR;
	
	s->data[++(s->top)] = data;
	return ERROR;
}

//出栈
int pop(Stack *s, StackData *x)
{
	if(s == NULL || s->top == -1)
		return ERROR;
	
	*x = s->data[(s->top)--];
	return OK;
}

//获取栈顶元素
int GetTop(Stack *s)
{
	if(s == NULL)
		return ERROR;
	return s->data[s->top];
}

//打印
void print(Stack s)
{
	int i;
	for (i = 0; i <= s.top; i++)
	{
		printf("%-4d", s.data[i]);
	}
	printf("\n");
}


int main()
{
	Stack s;
	Initstack(&s);
	
	int i;
	for (i = 1; i < 10; i += 2)
	{
		push(&s, i);
	}
	
	int num = GetTop(&s);
	printf("栈顶元素:%d\n", num);
	
	print(s);
	
	return 0;
}

链式栈

链式栈不存在满栈问题,空间可扩充,不需要头结点

插入和删除仅在栈顶处操作,链式栈的栈顶在链头。

空栈时 top = NULL

实例:
#include <stdio.h>
#include <stdlib.h>

#define ERROR 0
#define OK    1
//结点结构
typedef struct node
{
	int data;
	struct node *next;
}Node;

//链栈结构
typedef struct stack
{
	Node *top;
	int count;
}Stack;

//创建
Stack* Creat()
{
	Stack *p = (Stack*)malloc(sizeof(Stack));
	if(p == NULL)
		return NULL;
	p->top = NULL;
	p->count = 0;
	
	return p;
}

//添加
int push(Stack*s, int data)
{
	if(s == NULL)
		return ERROR;
	
	//新建结点
	Node *node = (Node*)malloc(sizeof(Node));
	if(node == NULL)
		return ERROR;
	
	node->data = data;
	//头插
	node->next = s->top;
	s->top = node;
	
	//节点数+1
	s->count++;
	
	return OK;
}

//出栈
int pop(Stack*s, int *x)
{
	if(s == NULL || s->top == NULL)
		return ERROR;
	
	Node* tmp = s->top;//记录原先链表的第一个结点
	*x = tmp->data;
	s->top = tmp->next;
	free(tmp);//释放原先第一结点空间
	
	s->count--;//节点数-1,否则pop过后在打印时会出现段错误
	
	return OK;
}

//打印数据
void print(Stack *s)
{
	if (NULL == s)
		return;
	int i;
	Node  *tmp = s->top;
	
	for(i = 1; i <= s->count; i++)
	//while(tmp != NULL),while好一些
	{
		printf("%-4d", tmp->data);
		tmp = tmp->next;
	}
	
	printf("\n");
	
}

int main()
{
	Stack *s = Creat();
	
	int i;
	for (i = 1; i < 10; i++)
	{
		push(s, i);
	}
	
	print(s);
	
	int x;
	for (i = 1; i < 10; i++)
	{
		pop(s, &x);
		printf("%d ", x);
	}
	/*
	pop(s, &x);
	printf("%d ", x);
	*/
	printf("\n");
	
	print(s);
	
	return 0;
}





  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值