#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #define ElementType int #define ERROR -1 /* 用链表表示栈 该栈初始是指向一个空节点 栈插入删除操作都是在链表头部形成栈结构 栈头一直指向链表第一个节点 */ 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){ return (S->Next == NULL); } bool Push(Stack S, ElementType X){ PtrToSNode q; q = (PtrToSNode)malloc(sizeof(struct SNode)); q->Data = X; q->Next = S->Next; S->Next = q; return true; } ElementType Pop(Stack S){ PtrToSNode FirstCell; ElementType TopElem; if(IsEmpty(S)){ printf("Stack is Empty\n"); return ERROR; }else{ FirstCell = S->Next; TopElem = FirstCell->Data; S->Next = FirstCell->Next; free(FirstCell); return TopElem; } } int main(){ ElementType a; Stack s = CreateStack(); Push(s, 0); Push(s, 1); a = Pop(s); printf("a = %d\n",a); Push(s, 2); a = Pop(s); printf("a = %d\n",a); a = Pop(s); printf("a = %d\n",a); a = Pop(s); return 0; }
浙公网安备 33010602011771号