欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C语言中栈的两种实现方法详解

时间:2022-06-30 09:29:03|栏目:C代码|点击:

一、顺序栈

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

//定义栈
typedef struct
{
	int data[maxsize];
	int top;
}sqstack,*sqslink;
//设置栈空
void Clearstack(sqslink s)
{
	s->top=-1;
}

//判断栈空
int Emptystack(sqslink s)
{
	if (s->top<0)
		return 1;
	else
		return 0;
}
//进栈
int Push(sqslink s, int x)
{
	if (s->top>=maxsize-1)
		return 0;
	else
	{
		s->top++;
		s->data[s->top]=x;
		return 1;
	}
}
// 出栈
int Popstack(sqslink s)
{
	int n;
	if (Emptystack(s)>0)
		return NULL;
	else
	{
		n=s->data[s->top];
		s->top--;
		return n;
	}
}
void main()
{
	sqslink s1;
	s1 =(sqslink)malloc(sizeof(sqstack));
	Clearstack(s1);
	printf("%d\n",s1->top);
	for(int i=0; i<=10;i++)
	{
		Push(s1, i);
		printf("%d is pushed into stack\n",i);
	}
	printf("top is point to %d\n",s1->top);
	printf("\n");
	int n;
	n = Popstack(s1);
	printf("number %d  is poped\n",n);
	printf("top is point to %d\n",s1->top);
}

二、链式栈

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

typedef struct node
{
	int data;
	struct node * next;
}snode,*slink;
struct Node
{
	slink i;
	slink n;
};

// 清空栈
void Clearstack(slink top)
{
	top=NULL;
}
//判断栈是否为空
int Emptystack(slink top)
{
	if (top==NULL) return 1;
	else return 0;
}

// 进栈
slink Push(slink top, int x)
{
	slink node = NULL;
	node = (slink)malloc(sizeof(snode));
	node->data = x;
	node->next = top;
	top = node;
	printf("*************************\n");
	printf("%d",top->data);
	printf("*************************\n");
	return top;
}
// 出栈
struct Node Pop(slink top)
{	
	slink node = NULL;
	struct Node result;
	if (Emptystack(top))
	{
	result.i=node;
	}
	else
	{
		int n;
		node = top;
		top = node->next;
		result.i = top;
		result.n = node;
		return result;
	}	
}

void main()
{
	slink top_ = NULL;
	for(int i =0; i<10;i++)
	{
		top_ = Push(top_, i);
		printf("%d is pushed in to the stack\n",i);
	}	
	int e;
	e = top_->data;
	printf("top is pointint to %d\n",e);
	printf("\n");
	printf("\n");
	printf("\n");
	slink node =NULL;
	printf("*************************\n");
	struct Node result = Pop(top_);
	if ((result.i)!=NULL)
	{
		top_ = result.i;
		node = result.n;

		e = top_->data;
		printf("top is pointint to %d\n",e);
		int e_node;
		e_node = node->data;
		printf("the node Poped 's data is pointint to %d\n",e_node);
		free(node);
	}
	else
	{
	printf("stack is empty");
	}
}

总结

上一篇:c语言 深入理解函数的递归

栏    目:C代码

下一篇:没有了

本文标题:C语言中栈的两种实现方法详解

本文地址:http://www.codeinn.net/misctech/206449.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有