链栈的实现
⑴ 建立一个空栈;
⑵ 对已建立的栈进行插入、删除、取栈顶元素等基本操作。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node,*LinkStack;
void initStack(LinkStack *top)
{
*top=(Node*)malloc(sizeof(Node));
(*top)->next=NULL;
}
void Push(LinkStack top,int n)
{
Node *temp;
temp=(Node *)malloc(sizeof(Node));
temp->data=n;
temp->next=top->next;
top->next=temp;
}
int Pop(LinkStack top,int *ptr)
{
int a;
Node *temp;
if((*top).next==NULL)
{
printf("下溢错误,删除失败\n");
return 0;
}
else
{
temp=top->next;
a=temp->data;
top->next=temp->next;
free(temp);
*ptr=a;
return 1;
}
}
int GetTop(LinkStack top,int *ptr)
{
if(top->next==NULL)
{
printf("下溢错误,取栈顶失败\n");
return 0;
}
else
{
*ptr=top->next->data;
return 1;
}
}
int Empty(LinkStack top)
{
if(top->next == NULL)
return 1;
else
return 0;
}
void DestoryStack(LinkStack top)
{
Node *p = top;
while(top!=NULL)
{
top = top->next;
free(p);
p = top;
}
}
int main()
{
int x;
LinkStack top;
initStack(&top);
printf("对15和10执行入栈操作\n");
Push(top,15);
Push(top,10);
if(GetTop(top,&x)==1)
printf("当前栈顶元素为:%d\n",x);
if(Pop(top,&x)==1)
printf("执行一次出栈操作,删除元素:%d\n",x);
if(GetTop(top,&x)==1)
printf("当前栈顶元素为:%d\n",x);
printf("请输入待插入元素:");
scanf("%d",&x);
Push(top,x);
if(Empty(top)==1)
printf("栈为空");
else
printf("栈非空");
DestoryStack(top);
return 0;
}