关于链式栈的基本代码的实现

栈是动态变化的结构,顺序栈在一定的程度上可以满足这种动态结构所要求的动态操作,但是以具有固定长度的数组来存储这种动态变化的数据结构是有局限性的。为了克服顺序栈的这个缺点,可以将栈用链式存储结构表示,这种存储结构的栈称为链栈。链栈即采用链表作为存储结构实现的链栈,在一个链栈中,为了方便进行插入和删除操作,一般指定链表头为栈顶,链尾为栈底。

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

typedef struct node
{
	int data;
	struct node*next;
}NODE,* stacknode;

stacknode stack_creat()
{
	stacknode top;
	stacknode p;
	int a,n;
	top = NULL;
	printf("Please input the number of element\n");
	scanf("%d",&n);
	if(n > 0)
	{
		printf("please input the %dst element of stack\n",n);
		while(n > 0)
		{
			printf("please input the element\n");
			scanf("%d",&a);
			p = (stacknode)malloc(sizeof(NODE));
			p->data = a;
			p->next = top;
			top = p;
			n--;

		}
	}
	return top;
}

	stacknode stack_push(stacknode top,int x)
	{
		stacknode p;
		p = (stacknode)malloc(sizeof(NODE));
		p->data = x;
		p->next = top;
		top = p;
		return(top);
	}

stacknode stack_pop(stacknode top,int x)
	{
		stacknode q;
		if(top != NULL)
		{
			q = top;
			x = top->data;
			top = top->next;
			free(q);
		}
		return(top);
	}

	void print(stacknode top)
	{
		stacknode p;
		p = top;
		if(p != NULL)
		{
			printf("output the stack\n");
			while(p != NULL)
		{
			printf("%-3d",p->data);
			p = p->next;
		}
		}
		else
		{
			printf("the stack is empty\n");
		}
	}

	int main()
	{
		int y = 0;
		stacknode L;
		L = stack_creat();
		print(L);
		putchar('\n');
		putchar('\n');
		printf("******the operation of pushstack\n****");
		printf("please input a element of the pushstack\n");
		scanf("%d",&y);
		L = stack_push(L,y);
		print(L);
		L = stack_pop(L,y);
		putchar('\n');
		putchar('\n');
		printf("******the operation of popstack****\n");
		printf("exput the element :%d\n",y);
		print(L);
	
	
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值