/*
*数据结构(栈):栈的链式存储结构
*用头插法建立的链栈,栈顶元素为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
本文介绍了一种使用头插法创建链栈的数据结构实现方法,并提供了完整的C语言代码示例。该链栈采用链表作为底层存储结构,支持基本的栈操作如入栈、出栈、获取栈顶元素等。
2155

被折叠的 条评论
为什么被折叠?



