欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈的链式存储结构(c语言实现)

程序员文章站 2022-06-05 14:47:26
...
#include <stdio.h>
#include <stdlib.h>

#define T 1
#define F 0

typedef int Status;
typedef int ElemType;

typedef struct StackNode//链式存储的结点
{
	ElemType data;//数据域
	struct  StackNode* next;//指针域
}StackNode, *LinkStackPtr;

typedef struct LinkStack//栈
{
	LinkStackPtr top;//top即栈顶 放在单链表的头部,对于链栈来说不需要头结点
	int count;//栈的长度
}LinkStack;

void init(LinkStack* S);
Status push(LinkStack* S, ElemType e);
Status pop(LinkStack* S, ElemType* e);
Status stackEmpty(LinkStack S);

int main()
{
	int i = 0, num = 0;
	LinkStack S;
	init(&S);
	for (; i < 10; i++)
	{
		push(&S, i);
	}
	for (; i > 0; i--)
	{
		pop(&S, &num);
		printf("%d\n", num);
	}
	return 0;
}

void init(LinkStack* S)//初始化为空栈
{
	S->top = NULL;
	S->count = 0;
}

Status push(LinkStack* S, ElemType e)
{
	//和链表一样正常创建结点
	LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
	s->data = e;
	s->next = S->top;//往上入栈
	S->top = s;
	S->count++;
	return T;
}

Status pop(LinkStack* S, ElemType* e)
{
	LinkStackPtr p;
	if (stackEmpty(*S))//S是地址 要传值
	{
		return F;
	}
	*e = S->top->data;
	p = S->top;
	S->top = S->top->next;
	free(p);//释放出栈结点
	S->count--;
	return T;
}

Status stackEmpty(LinkStack S)
{
	if (0 == S.count)
	{
		return T;
	}
	else
	{
		return F;
	}
}

运行结果:

栈的链式存储结构(c语言实现)

另一种简便表示:

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

#define T 1
#define F 0

typedef struct Node
{
	int value;
	struct Node *next;
}Node;

typedef struct 
{
	Node *top;
	int count;
}Stack;

int init(Stack *s);
int push(Stack *s, int e);
int pop(Stack *s, int *e);

int main()
{
	int i, e;
	Stack s;
	init(&s);
	for (i = 0; i < 5; i++)
	{
		push(&s, i);
		pop(&s, &e);
		printf("%d\n", e);
	}
	return 0;
}

int init(Stack *s)
{
	s->top = NULL;//初始化为空栈
	s->count = 0;
	return T;
}

int push(Stack *s, int e)
{
	Node *newNode = (Node*)malloc(sizeof(Node));
	if (NULL == newNode)
	{
		return F;
	}
	newNode->next = s->top;
	newNode->value = e;
	s->top = newNode;
	s->count ++;
	return T;
}

int pop(Stack *s, int *e)
{
	Node *temp = NULL;
	if (0 == s->count)
	{
		return F;
	}
	temp = s->top;
	*e = temp->value;
	s->top = temp->next;
	free(temp);
	s->count --;
	return F;
}

运行结果:

栈的链式存储结构(c语言实现)

相关标签: 数据结构