LinkedStack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
struct node
{
char data;
struct node *next;
};
typedef struct node LStackNode;
typedef struct node* LinkStack;
//初始化链栈
void InitStack(LinkStack *top)
{
if((*top = (LinkStack)malloc(sizeof(LStackNode))) == NULL)
exit(-1);
(*top)->next = NULL;
}
//判断链栈是否为空
int StackEmpty(LinkStack top)
{
if(top->next == NULL)
return 1;
else
return 0;
}
//进栈
int PushStack(LinkStack top,char e)
{
LStackNode *p;
if((p = (LStackNode*)malloc(sizeof(LStackNode))) == NULL)
{
printf("内存分配失败");
exit(-1);
}
p->data = e;
p->next = top->next;
top->next = p;
return 1;
}
//出栈
int PopStack(LinkStack top, char* e)
{
LStackNode* p;
p = top->next;//栈顶
if(!p)
{
printf("已经是空栈");
return -1;
}
top->next = p->next;
*e = p->data;
free(p);
return 1;
}
//取栈顶元素
int GetTop(LinkStack top,char *e)
{
LStackNode *p;
p = top->next;
if(!p)
{
printf("已经是空栈");
return -1;
}
*e = p->data;
return 1;
}
//求链栈长度
int StackLength(LinkStack top)
{
LStackNode *p;
int count = 0;
p = top;
while(p->next != NULL)
{
p = p->next;
count++;
}
return count;
}
//销毁链栈
void DestroyStack(LinkStack top)
{
LStackNode *p,*q;
p = top;
while(!p)
{
q = p;
p = p->next;
free(q);
}
}
LinkedStack.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"LinkedStack.h"
int main()
{
LinkStack S;
LStackNode* s;
char ch[50],e,*p;
InitStack(&S);
printf("请输入进栈的字符:\n ");
gets(ch);
p = &ch[0];
while(*p)
{
PushStack(S,*p);
p++;
}
printf("当前的栈顶元素:");
GetTop(S,&e);
printf("%4c\n",e);
printf("当前栈中的元素个数:%d\n",StackLength(S));
printf("元素的出栈顺序是:");
while(!StackEmpty(S))
{
PopStack(S,&e);
printf("%4c",e);
}
printf("\n");
return 0 ;
}