#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; }
链式栈相比较顺序栈,可以动态的分配,大小不受限制
链式栈的复习
最新推荐文章于 2022-09-08 22:18:10 发布