#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node * pnext;
}Node;
typedef struct stack
{
Node *top;
Node *bottom;
}Stack;
void init(Stack *S);
void push(Stack *S,ElemType value);
void traverse(Stack *S);
bool pop(Stack *S,ElemType *value);
bool empty(Stack *S);
void clear(Stack *S);
int main()
{
Stack S;
ElemType value;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
traverse(&S);
pop(&S,&value);
printf("%d\n",value);
traverse(&S);
clear(&S);
return 0;
}
void init(Stack *S)
{
S->top = (Node*)malloc(sizeof(Node));
S->bottom = S->top;
S->bottom->pnext = NULL;
}
void push(Stack *S,ElemType value)
{
Node *p = (Node*)malloc(sizeof(Node));
p->data = value;
p->pnext = S->top;
S->top = p;
}
void traverse(Stack *S)
{
Node *p = S->top;
while(p!=S->bottom)
{
printf("%d ",p->data);
p = p->pnext;
}
printf("\n");
}
bool empty(Stack *S)
{
return (S->top == S->bottom);
}
bool pop(Stack *S,ElemType *value)
{
if(empty(S))
{
return false;
}
else
{
Node *p = S->top;
*value = p->data;
S->top = S->top->pnext;
free(p);
return true;
}
}
void clear(Stack *S)
{
if(empty(S))
return;
else
{
Node *p = S->top;
while(p != S->bottom)
{
S->top = S->top->pnext;
free(p);
p = S->top;
}
printf("finish clear\n");
}
}
链栈的基本操作
最新推荐文章于 2024-07-03 16:45:04 发布