链栈的建立与基本操作

一、链栈的建立

1.定义结点结构体,含有数据和指针两个成员变量;

2.定义栈结构体,含有栈顶指针和栈中元素个数两个成员变量,其中栈顶指针是结点结构体指针类型;

3.栈顶指针当作头指针指向第一个元素,利用头插法实现入栈;

二、代码如下

/*
项目名称:链栈的建立与基本操作

编译环境:VC++ 2008

作者相关:。。。

最后修改:2019.6.21


学习目标:初始化、销毁、清空、判空、求长、返回栈顶元素、插入元素、删除元素、输出栈中元素

注意事项:1.测试所有功能是否正常

*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define OK         1
#define ERROR      0

typedef int  ElemType;
typedef bool Status;

//定义结点
typedef struct SNode{

	ElemType data;
	struct SNode *next;

}SNode,*SLNode;

//定义栈
typedef struct{

	SLNode top;//top指针指向栈顶元素
	int   count;//记录栈中元素个数

}SLinkStack;

Status Init_LStack(SLinkStack *s);

Status Clear_LStack(SLinkStack *s);

Status Destroy_LStack(SLinkStack *s);

Status Empty_LStack(SLinkStack s);

int    Length_LStack(SLinkStack s);

Status GetTop_LStack(SLinkStack s,ElemType *e);

Status Push(SLinkStack *s,ElemType e);//在栈顶插入元素,相当于不带头结点的头插法

Status Pop(SLinkStack *s,ElemType *e);

Status visit(ElemType c);

Status Out_LStack(SLinkStack s);

int main()
{
	SLinkStack s;
	ElemType e;

	if(Init_LStack(&s))
		printf("初始化成功!\n\n");
	else
		printf("初始化失败!\n\n");

	if(Empty_LStack(s))
		printf("栈为空!\n\n");
	else
		printf("栈非空!\n\n");

	srand(time(0));
	for(int i=0;i<5;i++)
	{
		e = rand()%20+1;
		Push(&s,e);
	}
	Out_LStack(s);

	int k=Length_LStack(s);
	printf("栈的长度为:%d \n\n",k);

	GetTop_LStack(s,&e);
	printf("栈顶元素为:%d \n\n",e);

	Pop(&s,&e);
	printf("删除的元素为:%d \n\n",e);

	Out_LStack(s);

	Clear_LStack(&s);

	Destroy_LStack(&s);

	return 0;
}

Status Init_LStack(SLinkStack *s)
{
	s->top=(SLNode)malloc(sizeof(SNode));
	if(!s)
		return ERROR;

	s->top = NULL;
	s->count = 0;

	return OK;
}

Status Clear_LStack(SLinkStack *s)
{
	SLNode p,q;
	p = s->top;

	while(p)
	{
		q = p;
		p = p->next;
		free(q);
	}
	s->top = NULL;
	s->count = 0;

	return OK;
}

Status Destroy_LStack(SLinkStack *s)
{
	SLNode p,q;
	p = s->top;

	while(p)
	{
		q = p;
		p = p->next;
		free(q);
	}
	free(s->top);//销毁最初创建的结点

	return OK;
}

Status Empty_LStack(SLinkStack s)
{
	if(s.count == 0)
		return true;
	else
		return false;
}

int    Length_LStack(SLinkStack s)
{
	return s.count;
}

Status GetTop_LStack(SLinkStack s,ElemType *e)
{
	if(s.top==NULL)
		return ERROR;
	else
		*e = s.top->data;

	return OK;
}

Status Push(SLinkStack *s,ElemType e)
{
	SLNode p;
	p = (SLNode)malloc(sizeof(SNode));
	if(!p)
		return ERROR;
	p->data = e;
	p->next = s->top;
	s->top  = p;
	s->count++;

	return OK;
}

Status Pop(SLinkStack *s,ElemType *e)
{
	SLNode p;

	if(s->top==NULL)
		return ERROR;

	*e = s->top->data;
	p  = s->top;
	s->top  = s->top->next;//这是链表,不能用--
	free(p);
	s->count--;

	return OK;
}

Status visit(ElemType c)
{
	printf("%d ",c);
	return OK;
}

Status Out_LStack(SLinkStack s)
{
	SLNode p=s.top;

	printf("栈内容为: ");
	while(p)
	{
		visit(p->data);
		p = p->next;
	}

	printf("\n\n");

	return OK;
}

三、效果

猜你喜欢

转载自blog.csdn.net/Sruggle/article/details/93234996