堆栈的链表表示
#include "stdafx.h"
#include "malloc.h"
#include "stdlib.h"
typedef int DataType;
//定义结构体
typedef struct Node
{
DataType data;
struct Node* next;
}LSNode;
//堆栈的初始化
void StackInitiate(LSNode **head)
{
if((*head=(LSNode *)malloc(sizeof(LSNode)))==NULL)
exit(1);
(*head)->next=NULL;
}
//判断是否非空
int StackNotEmpty(LSNode *head)
{
if(head->next==NULL)
return 0;
else
return 1;
}
//堆栈入栈
int StackPush(LSNode *head,DataType x)
{
LSNode *q;
if((q=(LSNode *)malloc(sizeof(LSNode)))==NULL)
exit(1);
q->data=x;
q->next=head->next;
head->next=q;
return 1;
}
//堆栈删除最上的元素
int StackPop(LSNode *head,DataType *x)
{
LSNode *q;
q=head->next;
*x=q->data;
head->next=q->next;
free(q);
return 1;
}
//取栈顶元素
int StackTop(LSNode *head,DataType *d)
{
LSNode *p=head->next;
if(p==NULL)
{
printf("堆栈已经出错");
return 0;
}
*d=p->data;
return 1;
}
//删除空间
void Destory(LSNode *head)
{
LSNode *p,*p1;
p=head;
while(p!=NULL)
{
p1=p;
p=p->next;
free(p1);
}
}
int main(int argc, char* argv[])
{
LSNode *myLSNode;
int i,x;
StackInitiate(&myLSNode);
for(i=0;i<4;i++)
{
StackPush(myLSNode,i);
}
for(i=0;i<4;i++)
{
if(StackTop(myLSNode,&x)==0)
{
printf("error!\n");
return 0;
}
else
printf("%d",x);
}
if(StackPop(myLSNode,&x)!=1)
{
printf("delete error!\n");
return 0;
}
if(StackTop(myLSNode,&x)==0)
{
printf("error!\n");
return 0;
}
else
printf("%d",x);
return 0;
}
浙公网安备 33010602011771号