马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
typedef char SElemType ;
typedef struct StackNode
{
SElemType data;
struct StackNode *next;
}StackNode,*LinkStackPtr;
typedef struct LinkStack
{
LinkStackPtr top;
int count;
}LinkStack;
//栈指针初始化
void InitialStack(LinkStack *L)
{
L->top=NULL;
L->count=0;
return;
}
//栈状态
int StackEmpty(LinkStack *pS)
{
if(!pS->count)//若为空,则返回1
return 1;
else
return 0;//若非空,则返回0;
}
//压栈操作
int Push(LinkStack *pS,SElemType e)
{
//一般情况下,不存在栈满情况
LinkStackPtr s=(LinkStackPtr)malloc(sizeof(StackNode));
s->data = e;
s->next = pS->top;
pS->top=s;
pS->count++;
//free(s);
return 0;
}
//出栈操作
int Pop(LinkStack *pS,SElemType *e)
{
LinkStackPtr p;
if(StackEmpty(pS))
{
printf("栈为空!");
return 0;
}
*e=pS->top->data;
p = pS->top;
pS->top = p->next;
free(p);
pS->count--;
return 0;
}
//打印栈链
void PrintStackLink(LinkStack *pS)
{
LinkStackPtr L;
int i;
//i = pS->count;
L = pS->top;
if(pS->count == 0)
{
printf("栈为空!");
return;
}
for(i=0;i<(pS->count);i++)
{
printf("%c\n",L->data);
L = L->next;
}
return ;
}
void main()
{
//测试
char getch;
char outch;
LinkStack myStack;
InitialStack(&myStack);
//压栈
printf("请输入压入栈的数据(char型),输入#结束");
scanf("%c",&getch);
while(getch!='#')
{
Push(&myStack,getch);
scanf("%c",&getch);
}
printf("栈链内容为:\n");
PrintStackLink(&myStack);
//出栈
while(!StackEmpty(&myStack))
{
Pop(&myStack,&outch);
printf("弹出内容为:%c\n",outch);
}
PrintStackLink(&myStack);
return ;
}
|