栈的链式存储算法——C语言版

栈的链式存储算法——C语言版

链栈和顺序表的链表是差不多


//栈的链式结构算法
#include
#include
#define MaxSize 10
typedef struct A
{
	int data;
	struct A* next;
}A,*a;
typedef struct B
{
	int top;
}B,*b;
bool chushihua(a& aa)
{
	aa = (A*)malloc(sizeof(A));//创建了一个带头结点的
	if (aa == NULL) return false;
	aa->next = NULL;
	return true;
}
bool charuyuansu(a& aa)
{
	a p = aa;
	for (int i = 1; i <= 5; i++)//尾插法
	{
		a b = (a)malloc(sizeof(A));
		b->data = i;
		b->next = p->next;//b->next = NULL;一样
		p->next = b;
		p = p->next;
	}
	//free(p);
	/*
	for (int i = 1; i <= 5; i++)//头插法
	{
		a b = (a)malloc(sizeof(A));
		b->data = i;
		b->next = aa->next;
		aa->next = b;
	}
	*/
	return true;
}
void chuzhan(a aa,int &e)
{
	/*while (aa->next)
	{*/
		aa = aa->next;
		e = aa->data;
	//}
}
bool charu(a aa, int i, int k)
{
	a p = aa;
	for (int j = 0; j < i-1; j++)
	{	
		p = p->next;
	}
	a b = (a)malloc(sizeof(A));
	b->data = k;
	b->next = p->next;
	p->next = b;
	return true;
}
int main()
{
	a aa;
	if (chushihua(aa)) printf("初始化链栈成功\n");
	else printf("初始化链栈失败");
	if (charuyuansu(aa))
	{
		printf("插入成功,栈为:");
		//for (int i = 0; i < 5; i++)
		a c = aa;
		while(c->next)
		{
			c = c->next;
			printf("%d",c->data);
		}
		printf("\n");
	}
	int e = 0;
	chuzhan(aa,e);
	printf("栈顶元素是:%d\n",e);
	int i = 3;
	int r = 404;
	if (charu(aa, i, r))
	{
		printf("插入成功,插入之后元素是:\n");
		a cc = aa;
		while (cc->next)
		{
			cc = cc->next;
			printf("%d  ", cc->data);
		}
		printf("\n");
	}
	return 0;
}

栈的链式存储算法——C语言版_第1张图片

你可能感兴趣的:(算法)