//只在一端(栈顶)插入、删除(后进先出)
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct SNode* PtrToNode;
struct SNode
{
ElemType data;
PtrToNode next;
};
typedef PtrToNode Stack;
int IsEmpty(Stack S); //测试站是否空栈
Stack CreateStack(); //创建一个空栈
void Push(ElemType x, Stack S); //进栈
int Top(Stack S); //返回栈顶元素
void Pop(Stack S); //出栈
void MakeEmpty(Stack S); //初始化栈
void DisposeStack(Stack S); //销毁栈
int main() {
//测试
Stack S;
S = CreateStack();
for (int i = 0; i != 6; ++i) {
Push(i, S);
}
Pop(S);
printf("%d %dn", S->data, Top(S));
MakeEmpty(S);
printf("%dn", S->data);
MakeEmpty(S);
return 0;
}
int IsEmpty(Stack S) {
return S->next == NULL;
}
Stack CreateStack() {
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S->data = 0; //头结点数据表示栈内元素个数
S->next = NULL;
return S;
}
void Push(ElemType x, Stack S) {
PtrToNode TmpCell;
TmpCell = (Stack)malloc(sizeof(struct SNode));
TmpCell->data = x;
TmpCell->next = S->next;
S->next = TmpCell;
(S->data)++;
}
int Top(Stack S) {
if (!IsEmpty(S))
return S->next->data;
else
printf("Empty Stack!n");
}
void Pop(Stack S) {
PtrToNode FirstCell;
if (!IsEmpty(S)) {
FirstCell = S->next;
S->next = S->next->next;
free(FirstCell);
(S->data)--;
}
else
printf("Empty Stack!n");
}
void MakeEmpty(Stack S) {
if (IsEmpty(S))
printf("The Stack is Emptyn");
else
while (!IsEmpty(S))
Pop(S);
}
void DisposeStack(Stack S) {
Stack TmpS;
if (IsEmpty(S)) {
TmpS = S;
free(TmpS);
}
else {
while (!IsEmpty(S))
Pop(S);
TmpS = S;
free(TmpS);
}
}
数据结构栈的操作_数据结构-栈(链栈)的基本操作(带头结点)
最新推荐文章于 2024-01-23 21:08:19 发布