链式栈的复习

#ifndef __LINKSTACK_H___
#define __LINKSTACK_H___

#define TRUE    1
#define FALSE   0
#include "error.h"
typedef int StackData;
typedef struct _node
{
	StackData data;
	struct _node *next;
}Node;
typedef struct _linkstack
{
	Node *top;
}LinkStack;
LinkStack* Create_Stack();


int InitStack ( LinkStack *s );

int Push ( LinkStack *s, StackData x ); 

int StackEmpty (LinkStack *s);

int Pop (LinkStack *s, StackData *x);

int Get_Top (LinkStack *s, StackData *x);


#endif

#include "LinkStack.h"#include <stdlib.h>LinkStack *Create_Stack(){LinkStack *s = (LinkStack *)malloc(sizeof(LinkStack)/sizeof(char));if(s == NULL){errno = MALLOC;return NULL;}return s;}int StackEmpty (LinkStack *s){if(s == NULL){errno = ERROR;return FALSE;}return (s->top == NULL);}int InitStack ( LinkStack *s ) {if(s == NULL){errno = ERROR;return FALSE;} s->top = NULL;return TRUE;}int Push ( LinkStack *s, StackData x ) {if(s == NULL){errno = ERROR;return FALSE;} Node *node = (Node *) malloc(sizeof (Node)/sizeof (char));if(node == NULL){errno = MALLOC;return FALSE;} node->data = x; node->next = s->top; s->top = node; return TRUE;}int Pop (LinkStack *s, StackData *x){if(s == NULL){errno = ERROR;return FALSE;}if(StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}Node *p = s->top;*x = s->top->data;s->top = p->next;free(p);return TRUE;}int Get_Top (LinkStack *s, StackData *x){if(s == NULL){errno = ERROR;return FALSE;}if(StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}*x = s->top->data;return TRUE;}int Destroy(LinkStack *s){if(s == NULL){errno = ERROR;return FALSE;}int x;while(StackEmpty(s) != TRUE){Pop(s,&x);}free(s);return TRUE;}


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

int main()
{
	LinkStack *s = Create_Stack();
	if(s == NULL)
	{
		myError("Create_Stack");
		return FALSE;
	}
	InitStack(s);
	
	if(StackEmpty(s))
		printf("空栈\n");
	
	int i;
	for(i=0; i<10; i++)
	{
		Push(s, i);
	}
	int x;
	char str[100];
	for(i=0; i<12; i++)
	{
		if(Pop(s, &x)==FALSE)
		{
			sprintf(str,"Pop第%d个元素",i);
			myError(str);
		}
		printf("x: %d\n",x);
	}
	
	if(Destroy(s) == FALSE)
	{
		myError("Destroy");
	}
	return 0;
}
链式栈相比较顺序栈,可以动态的分配,大小不受限制



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值