栈的基本操作

//栈的初始化,进栈,出栈,遍历栈,清空栈
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node
{
	int data;
    Node *next; 
}*pNode;

typedef struct Stack
{
	pNode ptop;
	pNode pBottom;
}STACK,*pStack;

//-------------------------
//栈的初始化(指针都要初始化)
void init(pStack ps)
{
   ps->ptop=(pNode)malloc(sizeof(Node));
   if(ps->ptop== NULL)
   {
	   printf("初始化失败\n");
	   exit(-1);
   }
   else
   {
	   ps->pBottom=ps->ptop;   //当插入多组数据时,是往上堆栈,所以将ptop作为结束地址
	   ps->ptop->next=NULL;
   }
}

//插入元素到栈顶
void push(pStack ps,int value)
{ 
	pNode pNew = (pNode)malloc(sizeof(Node));
    pNew->data=value;
	pNew->next=ps->ptop;      //链接下个栈的链
	ps->ptop=pNew;
}

//遍历栈 即将栈都输出一遍
void travel(pStack ps)
{
    pNode s=ps->ptop;
	printf("所有元素为:");
	while (s!=ps->pBottom)
	{
		printf("%d\t",s->data);
		s=s->next;
	}
	printf("\n");
}

//判断栈是否为空栈
int empty(pStack ps)
{
	if (ps->pBottom == ps->ptop)
	{
		printf("空栈");
		return 1;
	}
	else
		return 0;
}

//所谓出栈即将删除栈顶的数据
bool pop(pStack ps,int *val)
{
    if (empty(ps))
    {
		return false;
    }
	else
	{
		pNode p=ps->ptop;
		*val = ps->ptop->data;
		ps->ptop=ps->ptop->next;
		free(p);   //指针p被free或者delete之后,没有置为NULL,让人误以为p是个合法的指针。
		p=NULL;    //别看free和delete的名字恶狠狠的(尤其是delete),它们只是把指针所指的内存给释放掉,但并没有把指针本身干掉
		return true;
	}
}

//清空栈
void clear(pStack ps)
{
    pNode p=ps->ptop;
	pNode q=NULL;

	while (p != ps->pBottom)
	{
		q=p->next;
		free(p);
		p = q;
	}
	ps->ptop=ps->pBottom;
}

int main()
{
    //pStack ps=NULL;//出错
	int val;//int *val;  一开始这样写,太蠢了
    STACK ps;
	init(&ps);
    push(&ps,1);
	push(&ps,2);
	push(&ps,3);
	push(&ps,4);
	push(&ps,5);
	push(&ps,6);

    travel(&ps);
    
	if(pop(&ps,&val))
	{
       printf("遍历成功出栈元素为: %d\n",val);
	}
	else
	{
       printf("遍历失败\n");
	}
	travel(&ps);
	clear(&ps);
    printf("清空栈后");
    travel(&ps);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值