用C语言实现链栈的基本操作
#include <stdio.h>
#include <malloc.h>
#define ElemType char//相当于ElemType等同于char类型
//链式结构 =数据域+指针域
typedef struct LinkStackNode//定义一个链栈的结构体类型
{
ElemType data;//ElemType是链栈的元素类型,代表数据域
struct LinkStackNode* next;//代表指针域
}LinkStackNode;
typedef struct LinkStack//代表链栈的头结点
{
LinkStackNode* head;
}LinkStack;
//判断链栈是否为空
int StackEmpty(LinkStack* s)
{
if (s->head == NULL)
return 1;
else
return 0;
}
//链栈的初始化
void InitStack(LinkStack* s)
{
s->head = NULL;
}
//链栈进栈操作
void Push(LinkStack* s, ElemType x)
{
LinkStackNode* p;
p = (LinkStackNode*)malloc(sizeof(LinkStackNode));//为这个链栈申请内存
p->data = x;//将数据x放入链栈中
p->next = s->head;//指向下一个指针域
s->head = p;
}
//链栈出栈操作
void Pop(LinkStack* s)
{
if (StackEmpty(s))//表示这个链栈是空栈
{
printf("栈空");
}
LinkStackNode* p = s->head;
s->head = p->next;
}
//遍历打印链栈
void printLinkStack(LinkStack* s)
{
LinkStackNode* p = s->head;
while (p != NULL)
{
printf("%c ", p->data);//因为前面是char类型,所以这用%c
p = p->next;//指向下一个数据域
}
printf("\n");
}
//栈顶操作
int GetTop(LinkStack*s)
{
if (StackEmpty(s))//表示这个链栈是空栈
{
printf("栈空");
return 0;
}
return s->head->data;//s->head->data就是栈顶元素
}
//求链栈长度
int Getlength(LinkStack* s)
{
int length = 0;//先赋初值
LinkStackNode* p = s->head;
while (p != NULL)//链栈不为空,遍历循环整个链栈
{
length++;
p = p->next;//指向下一个数据域
}
return length;
}
int main()
{
ElemType e;
LinkStack s;
InitStack(&s);
printf("栈%s\n", (StackEmpty(&s) == 1 ? "空" : "不空"));
printf("a进栈\n");
Push(&s,'a');
printf("b进栈\n");
Push(&s,'b');
printf("c进栈\n");
Push(&s,'c');
printf("d进栈\n");
Push(&s,'d');
printf("打印当前链栈里面的元素:\n");
printLinkStack(&s);
printf("进行出栈操作:\n");
Pop(&s);
printLinkStack(&s);
printf("栈顶的元素为%c", GetTop(&s));
printf("\n");
printf("此时链栈的长度为:%d", Getlength(&s));
return 0;
}
运行结果: