2.2链栈的表示与实现
采用链式存储方式的栈称为链栈或者链式栈。设置头结点。并且一般top指向头结点。
代码实现:
LinkStack.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
typedef char DataType;
typedef struct node
{
DataType data;
struct node* next;
}LStackNode,*LinkStack;
//初始化
void InitStack(LinkStack *top)
{
*top = (LinkStack)malloc(sizeof(LinkStack));
if (top==NULL)
{
exit(-1);
}
(*top)->next = NULL;
}
//判空
int StackEmpty(LinkStack top)
{
if (top->next == NULL) //为空返回1否则返回0
return 1;
else
return 0;
}
//获取栈顶元素
int GetTop(LinkStack top,DataType* e)
{
LStackNode* p;
p = top->next;
if (!p) {
printf("栈已空!!!");
return 0; //成功返回1否则返回0
}
*e = p->data;
return 1;
}
//在栈中插入元素
int PushStack(LinkStack top,DataType e)
{
LStackNode* p;
p = (LStackNode *)malloc(sizeof(LStackNode));
if (!p)
{
printf("内存分配失败!!!");
return 0;
exit(-1);
}
p->data = e;
p->next = top->next;
top->next = p; //成功返回1否则返回0
return 1;
}
//弹出栈顶元素
int PopStack(LinkStack top,DataType *e)
{
LStackNode* p;
p = top->next;
if (top->next==NULL)
{
printf("栈已空!!!");
return 0; //成功返回1否则返回0
}
top->next = p->next;
*e = p->data;
free(p);
return 1;
}
//获取栈长度
int StackLength(LinkStack top)
{
LStackNode* p;
p = top->next;
int count = 0;
while (p)
{
p = p->next;
count++;
}
return count;
}
//清空栈
void ClearStack(LinkStack top)
{
LStackNode* p, * q;;
p = top;
while (p)
{
q = p;
p = p->next;
free(q);
}
}
test.c
#include <stdio.h>
#include <stdlib.h>
#include "LinkStack.h"
void main()
{
LinkStack S;
LStackNode* s;
DataType ch[50], e, * p;
InitStack(&S);
printf("请输入进栈的字符:\n");
gets(ch);
p = &ch[0];
while (*p)
{
PushStack(S, *p);
p++;
}
printf("元素出栈的序列是:");
while (!StackEmpty(S))
{
PopStack(S, &e);
printf("%4c",e);
}
printf("\n");
}