首页

2010年5月29日星期六

C语言实现堆栈(栈)的数据结构

#include
#include
#include
#define elemtype int
struct Node{
elemtype data;
struct Node *next;
};

struct stack{
struct Node *top;//栈顶指针
};
elemtype getTop(struct stack *s)
{//返回栈顶指针元素
if(s->top==NULL)
printf("The stack is empty\n");
return s->top->data;
}
struct stack * createstack()
{/*创建一个堆栈*/
struct stack *s;
s=(struct stack *)malloc(sizeof(struct stack));
s->top=NULL;
return s;
}
struct stack * push(struct stack *s,elemtype e)
{//向栈顶插入一个结点
struct Node *newptr;//指向新结点的指针
newptr=malloc(sizeof(struct Node));
assert(newptr!=NULL);
newptr->data=e;
newptr->next=NULL;
newptr->next=s->top;
s->top=newptr;
return s;
}
struct stack * pop(struct stack *s,elemtype *e)
{//删除栈顶元素,并将值存入e中
struct Node *temp=s->top;
*e=s->top->data;
s->top=s->top->next;
free(temp);
return s;
}
int empty(struct stack *s)
{
return s->top==NULL;
}
void printstack(struct stack *s)
{
if(s->top==NULL)
printf("the queue is empty.\n");
else
{
struct Node *p;
p=s->top;
printf("the stack is:\n");
while(p!=NULL)
{
printf("%d-->",p->data);
p=p->next;
}
}
}
int main()
{
struct stack *s;
int e;
s=createstack();
s=push(s,1);
s=push(s,2);
s=push(s,3);
s=push(s,4);
printstack(s);
s=pop(s,&e);
printstack(s);
return 0;
}

文章出处:http://www.diybl.com/course/3_program/c++/cppsl/2008127/97790.html

没有评论:

发表评论