堆栈(Stack):具备必定操做约束的线性表数组
类型名称:堆栈(stack)ide
数据对象集:一个有0个或多个元素的又穷线性表。spa
操做集:长度为MaxSize的堆栈S∈Stack,堆栈元素item∈ElementType3d
一、Stack CreateStack(int MaxSize):生成空堆栈,其最大长度为MaxSzie;指针
二、int IsFull(Stack S, int MaxSize):判断堆栈S是否已满code
三、void Push(Stack S, ElementType item):将元素item压入堆栈对象
四、int IsEmpty(Stack S):判断堆栈S是否为空blog
五、ElementType Pop(Stack S):删除并返回栈顶元素it
栈的顺序存储实现event
栈的顺序存储结构一般由一个一维数组和一个记录栈顶元素位置的变量组成。
#define MAXSIZE 100 typedef struct SNode *Stack; struct SNode{ ElementType Data[MAXSIZE]; int Top; }
入栈
void Push(Stack PtrS, ElementType item) { if(PtrS->Top == MAXSIZE - 1) { printf("Stack full"); return; } else { PtrS->Data[++(PtrS->Top)] = item; return; } }
出栈
ElementType Pop(Stack PtrS) { if(PtrS->Top == -1) { printf("Stack Empty"); return ERROR; } else return(PtrS->Data[(PtrS->Top)--]); }
例子:请用要给数组实现两个堆栈,要求最大地利用数组空间,使数组只要有空间入栈操做就能够成功。
1 #define MAXSIZE 100 2 struct DStack{ 3 ElementType Data[MAXSIZE]; 4 int Top1; 5 int Top2; 6 }S; 7 S.Top1 = -1; 8 S.Top2 = MAXSIZE; 9 10 void Push(struct DStack *PtrS, ElementType item, int Tag) 11 { 12 if(PtrS->Top2 - PtrS->Top1 == 1) { 13 printf("stack full"); 14 return; 15 } 16 if(Tag == 1) 17 PtrS->Data[++(PtrS->Top1)] = item; 18 else 19 PtrS->Data[--(PtrS->Top2)] = item; 20 } 21 22 ElementType Pop(stuct DStack *PtrS, int Tag) 23 { 24 if(Tag == 1) { 25 if(PtrS->Top == -1) { 26 ptintf("Stack1 Empty"); 27 return; 28 } else { 29 return(PtrS->Data[(PtrS->Top1)--]) 30 } 31 } else { 32 if(PtrS->Top2 == MAXSIZE) { 33 printf("Stack2 Empty"); 34 return; 35 } else { 36 return PtrS->Data[(PtrS->Top2)--]; 37 } 38 } 39 }
站的链式存储结构实际上就是一个单链表,叫作链栈。插入和删除操做智能在链栈的栈顶进行。栈顶指针Top应该在链表的哪一头?
typedef struct SNode *Stack; struct SNode{ ElementType Data; struct SNode *Next; };
堆栈初始化
Stack CreateStack() { Stack = s; S = (Stack)malloc(sizeof(struct SNode)); S->Next = NULL; return S; }
判断堆栈S是否为空
int IsEmpty(Stack S) { return (S->Next == NULL); }
push操做
void Push(ElementType item, Stack S) { struct SNode *TmpCell; TmpCell = (SNode)malloc(sizeof(struct SNode)); TmpCell->Data = item; TmpCell->Next = S->Next; S->Next = TmpCell; }
pop操做
ElementType Pop(Stack S) { struct SNode *FirstCell; ElementType TopElem; if(IsEmpty(S)) { printf("Stack Empty"); return NULL; } else { FirstCell = S->Next; S->Next = FirstCell->Next; TopElem = FirstCell->Data; free(FirstCell); return TopElem; } }