初始化一个链栈 ,将元素e,f,g,h,i依次进栈,获取栈顶元素,将栈中元素依次出栈并输出
链栈的表示
既采用链式储存结构实现的栈
具体代码
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int ElementType;
//定义
typedef struct node {
ElementType data;
struct node* next;
}StackNode, * LinkStack;
//判断是否为空
void InitStack(LinkStack top) {
top->next = NULL;
}
//初始化
int IsEmpty(LinkStack top) {
if (top->next == NULL)
return TRUE;
return FALSE;
}
//入栈
int Push(LinkStack top, ElementType element) {
LinkStack temp;
temp = (LinkStack)malloc(sizeof(StackNode));
temp->data = element;
temp->next = top->next;
top->next = temp;
return TRUE;
}
//出栈
int Pop(LinkStack top, ElementType* element) {
if (IsEmpty(top))
return FALSE;
StackNode* temp = top->next;
*element = temp->data;
top->next = temp->next;
free(temp);
return TRUE;
}
//获取栈顶
int GetTop(LinkStack top, ElementType* element) {
if (top->next == NULL)
return FALSE;
*element = top->next->data;
return TRUE;
}
int main(){
LinkStack s;
int i;
int result;
s = (LinkStack)malloc(sizeof(StackNode));
InitStack(s);
Push(s, 'e');
Push(s, 'f');
Push(s, 'g');
Push(s, 'h');
Push(s, 'i');
GetTop(s, &result);
printf("栈顶元素为:%c\n", result);
printf("元素依次出栈:\n");
while (!IsEmpty(s))
{
Pop(s, &result);
printf("%c\n", result);
}
}
最终效果