/*
*数据结构(栈):栈的链式存储结构
*用头插法建立的链栈,栈顶元素为S->next所指结点
*Date:2017/4/14
*/
#include <stdio.h>
#include <stdlib.h>
#define InitSize 100
#define ElemType char
typedef struct LNode{
ElemType data;
struct LNode *next;
int length;
}*LinkStack;
void createStack1(LinkStack &S); //头插法建立栈
ElemType getTop(LinkStack S); //取栈顶元素,返回其值
void push(LinkStack &S); //进栈
void pop(LinkStack &S); //出栈
bool emptyStack(LinkStack S); //判空操作
void clearStack(LinkStack &S); //清空栈
void destroyStack(LinkStack &S); //销毁栈
void createStack1(LinkStack &S){
ElemType ch;
S = (LinkStack)malloc(InitSize * sizeof(LNode));
S->next = NULL;
S->length = 0;
while(scanf("%c",&ch) != EOF && ch != '\n'){
LNode *p = (LNode *)malloc(sizeof(LNode));
if(S->length < InitSize){
p->data = ch;
p->next = S->next;
S->next = p;
S->length++;
}
}
}
ElemType getTop(LinkStack S){
return S->next->data;
}
void push(LinkStack &S,ElemType e){
if(S->length < InitSize){
LNode *p = (LNode *)malloc(sizeof(LNode));
p->data = e;
p->next = S->next;
S->next = p;
S->length++;
}
}
void pop(LinkStack &S,ElemType *e){
LNode *p = (LNode *)malloc(sizeof(LNode));
p = S->next;
*e = p->data;
S->next = p->next;
free(p);
S->length--;
}
bool emptyStack(LinkStack S){
if(S->next == NULL){
return true;
}else{
return false;
}
}
void clearStack(LinkStack &S){
ElemType e;
while(S->next != NULL){
pop(S,&e);
}
}
void destroyStack(LinkStack &S){
clearStack(S);
free(S);
printf("栈已经销毁\n");
}
int main(){
freopen("in.txt","r",stdin);
LinkStack S;
ElemType e;
createStack1(S);
printf("getTop(S):%c\n",getTop(S));
pop(S,&e);
printf("pop(S,&e):%c\n",e);
printf("getTop(S):%c\n",getTop(S));
push(S,'p');
printf("push(S,'p'):%c\n",getTop(S));
if(emptyStack(S)){
printf("S is NULL\n");
}else{
printf("S isn't NULL\n");
}
clearStack(S);
printf("clearStack(S):\n");
if(emptyStack(S)){
printf("S is NULL\n");
}else{
printf("S isn't NULL\n");
}
destroyStack(S);
return 0;
}
in.txt:
orange