//浙大数据结构 栈(链表)
#include<stdio.h>
#include<stdlib.h>
#include<crtdbg.h>
#define ERROR -1
typedef int ElementType;
typedef struct SNode *PtrToSNode;
struct SNode {
ElementType Data;
PtrToSNode Next;
};
typedef PtrToSNode Stack;
Stack CreateStack()
{ /* 构建一个堆栈的头结点,返回该结点指针 */
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S->Next = NULL;
return S;
}
bool IsEmpty(Stack S)
{ /* 判断堆栈S是否为空,若是返回true;否则返回false */
return (S->Next == NULL);
}
bool Push(Stack S, ElementType X)
{ /* 将元素X压入堆栈S */
PtrToSNode TmpCell;
TmpCell = (PtrToSNode)malloc(sizeof(struct SNode));
TmpCell->Data = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
return true;
}
ElementType Pop(Stack S)
{ /* 删除并返回堆栈S的栈顶元素 */
PtrToSNode FirstCell;
ElementType TopElem;
if (IsEmpty(S)) {
printf("堆栈空\n");
return ERROR;
}
else {
FirstCell = S->Next;
TopElem = FirstCell->Data;
S->Next = FirstCell->Next;
free(FirstCell);
return TopElem;
}
}
int main()
{
Stack S = CreateStack();
Push(S, 1);
Push(S, 2);
Push(S, 3);
Push(S, 4);
Push(S, 5);
while (S->Next)
{
printf("pop data:%d \n", Pop(S));
}
Pop(S);//堆栈空
free(S);
_CrtDumpMemoryLeaks(); //检查内存泄漏
system("pause");
return 0;
}
//浙大数据结构 栈(链表)
最新推荐文章于 2020-07-25 10:41:29 发布