链式栈

今天实现了下链式栈,比链表简单了些。

只写了其中的一部分操作

#include
#include
#include
typedef struct Node{
int data;
struct Node*pNext;
}NODE,*PNODE;
typedef struct stack{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
void init(PSTACK);
bool empty(PSTACK);
void traverse(PSTACK);
void push(PSTACK,int);
int pop(PSTACK);
void clear(PSTACK);
int main()
{
int val;
STACK s;
init(&s);
if(empty(&s))
printf("the stack is emptyn");
push(&s,1);
push(&s,2);
push(&s,3);
push(&s,4);
traverse(&s);
val=pop(&s);
printf("%dn",val);
traverse(&s);
clear(&s);
if(empty(&s))
printf("the stack is emptyn");
system("pause");
return 0;
}
void init(PSTACK s)//初始化,,严格的来说是创建并初始化
{
s->pTop=(PNODE)malloc(sizeof(NODE));
if(s->pTop==NULL)
{
printf("memory errorn");
exit(-1);
}
s->pBottom=s->pTop;
s->pTop->pNext=NULL;
return;
}
bool empty(PSTACK s)
{
if(s->pTop==s->pBottom)
return true;
else
return false;
}
void traverse(PSTACK s)//遍历输出元素值
{
if(empty(s))
return;
PNODE p;
p=s->pTop;
while(p->pNext!=NULL)
{
printf("%d ",p->data);
p=p->pNext;
}
printf("n");
return;
}
void push(PSTACK s,int val)
{
PNODE p=(PNODE)malloc(sizeof(NODE));
if(p==NULL)
{
printf("memory errorn");
exit(-1);

}
p->pNext=s->pTop;
p->data=val;
s->pTop=p;
return;
}
int pop(PSTACK s)
{
int val;
PNODE p=s->pTop;
s->pTop=p->pNext;
val=p->data;
free(p);
p=NULL;
return val;
}
void clear(PSTACK s)//清空栈
{
PNODE p,q;
if(empty(s))
return;
p=s->pTop;
q=NULL;
while(p!=s->Bottom)
{
q=p->pNext;
free(p);
p=q;

}
s->pTop=s->pBottom;
return;
}

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>