您的位置:首页 > 其它

链式堆栈的初始化、出栈、入栈、取栈顶元素、判空

2017-04-03 20:56 190 查看
#include<stdio.h>
#include<malloc.h>

typedef int DataType;
typedef struct snode    //定义结构体
{
DataType data;
struct snode *next;
}LSNode;

void InitStact(LSNode **head)   //初始化
{
*head = (LSNode *)malloc(sizeof(LSNode));
(*head)->next = NULL;
}

int NotEmpty(LSNode *head){          //判断堆栈是否为空
if(head->next == NULL){
return 0;
}
else{
return 1;
}
}
void Push(LSNode *head,DataType x)  //入栈
{
LSNode *p;
p = (LSNode *)malloc(sizeof(LSNode));
p->data = x;
p->next = head ->next;
head->next = p;
}

int Pop(LSNode *head,DataType *x){     //出栈
LSNode *p = head->next;
if(p == NULL){
printf("堆栈已空出错!");
return 0;
}
head->next = p->next;
*x = p->data;
free(p);
return 1;
}
int Top(LSNode *head, DataType *x){   //取栈顶元素
LSNode *p = head->next;
if(p == NULL){
printf("堆栈已空出错!");
return 0;
}
*x = p->data;
return 1;
}
int main()
{
LSNode *s;
int x;
InitStact(&s);
//	scanf_s("%d",&x);
for(x=0;x<10;++x)
{
Push(s,x+1);
}
Top(s,&x);
printf("%d \n",x);
while(NotEmpty(s))
{
Pop(s,&x);
printf("%d  ",x);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐