数据结构之栈的实现--链式栈(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40411915/article/details/82723236

基本操作

  1. 入栈
  2. 出栈
  3. 读栈顶元素值
  4. 建栈
  5. 栈空
  6. 销毁栈

 代码实现

建栈

int initLStack(pLStack list)
{
	if(!list)
		return 0;
	list->node = NULL ;
	list->length = 0;
	return 1;
}

栈空

int lStackEmpty(pLStack s)
{
	if(!s)
		return 0;
	return s->length == 0;
}

入栈

int push(pLStack s, int data)
{
	pNode newNode = NULL, pre = NULL;
	if(!s)
		return 0;
	newNode = s->node;
	while(newNode)
	{
		pre = newNode;
		newNode = newNode->next;
	}
	newNode = (pNode)malloc(sizeof(Node));
	newNode->data = data;
	newNode->next = NULL;
	if(!pre)
		s->node = newNode;
	else
		pre->next = newNode;
	s->length++;
	pre = NULL;
	return 1;
}

出栈

int pop(pLStack s, int* data)
{
	pNode p = NULL, pre = NULL;
	int i = 1;
	if(!s || lStackEmpty(s))
		return 0;
	pre = s->node;
	while(pre->next)
	{
		p = pre;
		pre = pre->next;
	}
	if(!p)
		s->node = NULL;
	else
		p->next = NULL;
	*data = pre->data;
	free(pre);
	pre = NULL;
	s->length--;
	return 1;
}

读栈顶元素值

int getTop(pLStack s, int* val)
{
	pNode p = NULL, pre=NULL;
	if(!s || lStackEmpty(s))
		return 0;
	p = s->node;
	while(p)
	{
		pre = p;
		p = p->next;
	}
	*val = pre->data;
	return 1;
}

销毁栈

int destroyStack(pLStack s)
{
	pNode p = NULL, q = NULL;
	if(!s || lStackEmpty(s))
		return 0;
	p = s->node;
	while(!p)
	{
		q = p;
		p = p->next;
		free(q);
		q = NULL;
	}
	s->node = NULL;
	s->length = 0;
	return 1;
}

 测试代码

#include <stdio.h>
#include "ListStack.h"

int main()
{
	int i = 0;
	int val = -1, tag = -1;
	ListStack stack;
	initLStack(&stack);
	for(i=1; i<11; ++i)
		push(&stack, i);
	pop(&stack, &tag);
	getTop(&stack, &val);
	printf("%d ... \n", val);

	return 0;
}

写在最后

 文章记录本人学习所得, 如有所错误, 欢迎留言指出交流, 大神请键盘下留人 ! ! ! 

猜你喜欢

转载自blog.csdn.net/weixin_40411915/article/details/82723236