C语言顺序栈与链式栈的代码实现


//链式栈
typedef struct LinkStack//创建结构体
{
	int data;
	struct LinkStack* lp;
}LS;
LS* Creat()//创建栈
{
	LS* head = (LS*)malloc(sizeof(LS));
	head->lp == NULL;
	return head;
}
LS* push(LS* head, int x)//压栈
{
	LS* node = (LS*)malloc(sizeof(LS));
	node->data = x;
	node->lp = head;
	head = node;
	printf("入栈成功!\n");
	return head;
}
LS* Out(LS *head,int *x)//出栈
{
	LS* tmp = head;
	if (head->lp == NULL)
	{
		printf("栈为空!\n");
		return 0;
	}
	else
	{
		*x = head->data;
		head = head->lp;
		free(tmp);
		return head;
	}
}
int main()
{
	LS* head = Creat();
	int val,n;
	printf("请输入想要录入的个数:\n");
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		printf("请输入需要录入的整数:\n");
		scanf("%d", &val);
		head = push(head, val);
	}
	for (int i = 0; i < n; i++)
	{
		int put;
		head=Out(head,&put);
		printf("元素出栈:%d ",put);
	}
	return 0;
}

顺序栈:

//顺序栈
#define MAX 100
typedef int DATA;
typedef struct stack {
	DATA data[MAX];
	int  top;
}Stack;
Stack* Creat()
{
	Stack* phead = (Stack*)malloc(sizeof(Stack));
	phead->top = -1;
	return phead;
}

void Push(Stack *phead,int x)
{
	if (phead->top == MAX - 1)
	{
		printf("栈满!\n");
		return;
	}
	else
	{
		phead->top++;
		phead->data[phead->top]=x;
		printf("入栈成功!\n");
	}
}
int Out(Stack* phead)
{
	int x=0;
	if (phead->top == -1)
	{
		printf("栈为空!\n");
		return 0;
	}
	else
	{
		x = phead->data[phead->top];
		phead->top--;
		return x;
	}
}
int main() 
{
	int n;
	Stack* phead = Creat();
	int val;
	printf("请输入想要录入的个数:\n");
	scanf("%d", &n);
	for(int i=0;i<n;i++)
	{
		printf("请输入需要录入的整数:\n");
		scanf("%d", &val);
		Push(phead, val);
	}
	for (int i = 0; i < n; i++)
	{
		
		int put = Out(phead);
		printf("%d ", put);
    }
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值