堆栈的定义与操作-顺序存储,链式存储(C语言)
生活随笔
收集整理的這篇文章主要介紹了
堆栈的定义与操作-顺序存储,链式存储(C语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
順序存儲:
typedef int Position; struct SNode {ElementType *Data; /* 存儲元素的數組 */Position Top; /* 棧頂指針 */int MaxSize; /* 堆棧最大容量 */ }; typedef struct SNode *Stack;Stack CreateStack( int MaxSize ) {Stack S = (Stack)malloc(sizeof(struct SNode));S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));S->Top = -1;S->MaxSize = MaxSize;return S; }bool IsFull( Stack S ) {return (S->Top == S->MaxSize-1); }bool Push( Stack S, ElementType X ) {if ( IsFull(S) ) {printf("堆棧滿");return false;}else {S->Data[++(S->Top)] = X;return true;} }bool IsEmpty( Stack S ) {return (S->Top == -1); }ElementType Pop( Stack S ) {if ( IsEmpty(S) ) {printf("堆棧空");return ERROR; /* ERROR是ElementType的特殊值,標志錯誤 */}else return ( S->Data[(S->Top)--] ); }鏈式存儲:
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("堆棧空"); return ERROR;}else {FirstCell = S->Next; TopElem = FirstCell->Data;S->Next = FirstCell->Next;free(FirstCell);return TopElem;} }總結
以上是生活随笔為你收集整理的堆栈的定义与操作-顺序存储,链式存储(C语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 现在腾讯又打算搞个大事腾讯搞事情
- 下一篇: 队列的定义与操作-顺序存储,链式存储(C