求栈的链式结构
求栈的链式结构,实现栈的初始化,插入,删除,输出。
好比如下的栈的顺序结构:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct {
ElemType elem[MAXSIZE];
int top;
}SqStack;
void OutStack(SqStack p);
void InitStack(SqStack *p);
void Push(SqStack *p,ElemType x);
ElemType Pop(SqStack *p);
ElemType GetTop(SqStack p);
void main()
{SqStack q;
int y,cord; ElemType a;
do{printf("\n");
printf("\n 主菜单\n");
printf("\n 1 初始化顺序栈 \n");
printf("\n 2 插入一个元素 \n");
printf("\n 3 删除栈顶元素 \n");
printf("\n 4 取栈顶元素 \n");
printf("\n 5 结束程序运行 \n");
printf("\n----------------------------\n");
printf("请输入您的选择(1,2,3,4,5)");
scanf("%d",&cord);
switch(cord)
{ case 1:{InitStack(&q); OutStack(q);
} break;
case 2:{printf("\n 请输入要插入的数据 a=");scanf("%d",&a);
Push(&q,a); OutStack(q);
}break;
case 3:{a=Pop(&q);printf("\n a=%d",a);
OutStack(q);
}break;
case 4:{y=GetTop(q);printf("\n y=%d",y);
OutStack(q);
}break;
case 5:exit(0);
}
}while(cord<=5);
}
void InitStack(SqStack *p)
{p->top=0;
}
void Push(SqStack *p,ElemType x)
{if(p->top<MAXSIZE-1){p->top=p->top+1; p->elem[p->top]=x;}
else printf("\n Overflow!");
}
ElemType Pop(SqStack *p)
{ElemType x;
if(p->top!=0){x=p->elem[p->top];
p->top=p->top-1;
return(x);
}
else{printf("\n Underflow!");
return(-1);
}
}
ElemType GetTop(SqStack p)
{ ElemType x;
if(p.top!=0){x=p.elem[p.top];
return(x);
}
else{printf("\n Underflow!");
return(-1);
}
}
void OutStack(SqStack p)
{int i;
if(p.top==0)printf("\n The Stack is NULL");
for(i=p.top;i>0;i--)
printf("\n %2d %6d",i,p.elem[i]);
}
[解决办法]
typedef int ElemType;
typedef struct _Node
{
ElemType data;
struct _Node *next;
}Node;
typedef struct
{
Node *top;
int len;
}stack;
void InitStack(stack& s)
{
s.len=0;
s.top=NULL;
}
void Push(stack& s,ElemType e)
{
Node *p=(Node*)malloc(sizeof(Node));
if (!p) return;
p.data=e;
p->next=s.top;
s.top=p;
s.len++;
}
void Pop(stack& s,ElemType& e)
{
if (s.len==0) return;
e=s.top->data;
Node *tmp=s.top;
s.top=s.top->next;
free(tmp);
s.len--;
}
void OutStack(stack s)
{
while(s.top)
{
printf("%d\n",s.top.data);
s.top=s.top->next;
}
}
栈的链式结构:An(栈顶)-->(指针指向)An-1-->.......A2-->A1; 与单向链表的指针指向是方向相反的
[解决办法]