实验三 链栈的操作
一、实验内容:
将单链表作为栈,写出初始化栈、判空栈、进栈和出栈操作。
二、实验目的
掌握初始化栈、判空栈、进栈和出栈的基本操作的实现
参考程序:
#include
#include
typedef struct node{
int value;
struct node *next;
}stackNode,*LinkStack;
void initStack(LinkStack &topPt)//初始化栈
{topPt=NULL;}
int isEmpty(LinkStack top)//判空栈
{return top==NULL;}
void push(LinkStack &topPt,int e)//进栈
{stackNode *p;
p=(stackNode*)malloc(sizeof(stackNode));
p->value=e;
p->next=topPt;
topPt=p;
}
int pop(LinkStack &topPt,int &vPt)//出栈
{stackNode *p;
if(isEmpty(topPt))return 0;
p=topPt;vPt=p->value;
topPt=p->next;
free(p);return 1;
}
void main()
{int choice=1,e,i;
LinkStack top,p;
initStack(top);
while(choice=4)
} {printf("\t1:push\n"); printf("\t2:pop\n"); printf("\t3:show the stack\n"); printf("\t4:exit\n"); scanf("%d",&choice); if(choice==1){printf("input an element(int):"); scanf("%d",&e); push(top,e); } else if(choice==2){i=pop(top,e); if(i==0)printf("Stack is empty\n"); else printf("the poped value is %d\n",e); } else if(choice==3){p=top; printf("all element:"); while(p) {printf("%3d",p->value); p=p->next; } } else if(choice!=4)printf("error\n"); }
实验三 链栈的操作
一、实验内容:
将单链表作为栈,写出初始化栈、判空栈、进栈和出栈操作。
二、实验目的
掌握初始化栈、判空栈、进栈和出栈的基本操作的实现
参考程序:
#include
#include
typedef struct node{
int value;
struct node *next;
}stackNode,*LinkStack;
void initStack(LinkStack &topPt)//初始化栈
{topPt=NULL;}
int isEmpty(LinkStack top)//判空栈
{return top==NULL;}
void push(LinkStack &topPt,int e)//进栈
{stackNode *p;
p=(stackNode*)malloc(sizeof(stackNode));
p->value=e;
p->next=topPt;
topPt=p;
}
int pop(LinkStack &topPt,int &vPt)//出栈
{stackNode *p;
if(isEmpty(topPt))return 0;
p=topPt;vPt=p->value;
topPt=p->next;
free(p);return 1;
}
void main()
{int choice=1,e,i;
LinkStack top,p;
initStack(top);
while(choice=4)
} {printf("\t1:push\n"); printf("\t2:pop\n"); printf("\t3:show the stack\n"); printf("\t4:exit\n"); scanf("%d",&choice); if(choice==1){printf("input an element(int):"); scanf("%d",&e); push(top,e); } else if(choice==2){i=pop(top,e); if(i==0)printf("Stack is empty\n"); else printf("the poped value is %d\n",e); } else if(choice==3){p=top; printf("all element:"); while(p) {printf("%3d",p->value); p=p->next; } } else if(choice!=4)printf("error\n"); }