堆栈的顺序存储实现
堆栈的顺序存储实现其实是利用了定长数组来模拟堆栈先进后出的规则,由此决定了堆栈的固定容量, 同时需要两个头尾指针来指示栈顶和栈底的位置。
以下展示各部分的代码实现。
1 2 3 4 5 6 7
| typedef int Position; struct QNode { ElementType *Data; Position Front, Rear; int MaxSize; }; typedef struct QNode *Queue;
|
1 2 3 4 5 6 7 8
| Queue CreateQueue( int MaxSize ) { Queue Q = (Queue)malloc(sizeof(struct QNode)); Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType)); Q->Front = Q->Rear = 0; Q->MaxSize = MaxSize; return Q; }
|
1 2 3 4
| bool IsFull( Queue Q ) { return ((Q->Rear+1)%Q->MaxSize == Q->Front); }
|
1 2 3 4 5 6 7 8 9 10 11 12
| bool AddQ( Queue Q, ElementType X ) { if ( IsFull(Q) ) { printf("队列满"); return false; } else { Q->Rear = (Q->Rear+1)%Q->MaxSize; Q->Data[Q->Rear] = X; return true; } }
|
1 2 3 4
| bool IsEmpty( Queue Q ) { return (Q->Front == Q->Rear); }
|
1 2 3 4 5 6 7 8 9 10 11
| ElementType DeleteQ( Queue Q ) { if ( IsEmpty(Q) ) { printf("队列空"); return ERROR; } else { Q->Front =(Q->Front+1)%Q->MaxSize; return Q->Data[Q->Front]; } }
|
堆栈的链式存储实现
堆栈的链式结构实现原理是将栈中的每一个元素视为链表中的每一个结点,利用链表的尾部的增删来实现先进后出的堆栈特点。
1 2 3 4 5 6
| typedef struct SNode * PtrToSNode; struct SNode { ElementType Data; PtrToSNode Next; }; typedef PtrToSNode Stack;
|
1 2 3 4 5 6 7 8
| Stack CreateStack( ) { Stack S;
S = (Stack)malloc(sizeof(struct SNode)); S->Next = NULL; return S; }
|
1 2 3 4
| bool IsEmpty ( Stack S ) { return ( S->Next == NULL ); }
|
1 2 3 4 5 6 7 8 9 10
| bool Push( Stack S, ElementType X ) { PtrToSNode TmpCell;
TmpCell = (PtrToSNode)malloc(sizeof(struct SNode)); TmpCell->Data = X; TmpCell->Next = S->Next; S->Next = TmpCell; return true; }
|
弹出栈顶元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| ElementType Pop( Stack S ) { PtrToSNode FirstCell; ElementType TopElem;
if( IsEmpty(S) ) { printf("堆栈空"); return ERROR; } else { FirstCell = S->Next; TopElem = FirstCell->Data; S->Next = FirstCell->Next; free(FirstCell); return TopElem; } }
|
Last updated:
Thanks for your reading :) | URL
https://joshuaqyh.github.io/2019/02/09/数据结构-堆栈-C语言实现顺序存储和链式存储/