数据结构入门-栈

前端之家收集整理的这篇文章主要介绍了数据结构入门-栈前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

定义:一种可以实现“先进后出”的存储结构

分类

  1. 静态栈
  2. 动态栈

算法:

  1. 出栈
  2. 压栈

代码实现:

多敲,多敲,后期改进

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


typedef struct Node
{
	int data;
	struct Node * pNext;
}NODE,* PNODE;


typedef struct Stack
{
	PNODE pTop;
	PNODE pBottom;
}STACK,* PSTACK;


void init(PSTACK);
void push(PSTACK,int);
void traverse(PSTACK);
bool pop(PSTACK,int *);
void clear(PSTACK pS);


int main(void)
{
	STACK S; // STACK等价于 struct Stack
	int val;

	init(&S); // 目的是造出一个空栈

	push(&S,1); // 压栈
	push(&S,8);
	push(&S,23);
	push(&S,26);
	push(&S,34);
	push(&S,45);
	push(&S,76);
	push(&S,88);
	traverse(&S); // 遍历输出

	if(pop(&S,&val))
	{
		printf("你删除的是%d\n",val );
		traverse(&S);
		printf("清空数据\n");
		clear(&S);
		traverse(&S);
	}
	else
	{
		printf("删除失败\n");
	}
}




void init(PSTACK pS)
{
	pS->pTop = (PNODE)malloc(sizeof(NODE));
	if (NULL == pS->pTop)
	{
		printf("动态内存分配失败\n");
		exit(-1);
	}
	else
	{
		pS->pBottom = pS->pTop;
		pS->pTop->pNext = NULL; // pS->pBottom->pNext = NULL
	}
}


void push(PSTACK pS,int val)
{
	PNODE pNew = (PNODE)malloc(sizeof(NODE));

	pNew->data = val; 

	pNew->pNext = pS->pTop; // 这里需要注意
	pS->pTop = pNew;

	return;
}


void traverse(PSTACK pS)
{
	PNODE p = pS->pTop;

	while(p != pS->pBottom)
	{
		printf("%d ",p->data);
		p = p->pNext;
	}

	printf("\n");
	return;
}


bool empty(PSTACK pS )
{
	if (pS->pTop == pS->pBottom)
		return true;
	else
		return false;

}


// 把pS所指向的栈出栈一次,并把出栈元素存下
bool pop(PSTACK pS,int *val)
{

	if (empty(pS))
	{
		return false;
	}
	else
	{
		PNODE p = pS->pTop;
		*val = p->data;

		pS->pTop = p->pNext;
		free(p);
		p = NULL;
		return true;

	}
	
}


// 清空
void clear(PSTACK pS)
{
	if (empty(pS))
	{
		return;
	}
	else
	{
		PNODE p = pS->pTop;
		PNODE q = NULL;

		while(p != pS->pBottom)
		{
			q = p->pNext;
			free(p);
			p = q;
		}

		pS->pTop = pS->pBottom;
	}
}

应用:

  1. 函数调用
  2. 中断
  3. 表达式求值
  4. 内存分配
  5. 缓冲处理
  6. 迷宫
原文链接:https://www.f2er.com/datastructure/993986.html

猜你在找的数据结构相关文章