栈的C语言实现(链表和数组)

数组栈的实现

stack_array.h

typedef int ElementType;typedef struct StackArrayNode{int Capacity;int TopOfStack;ElementType *Array;}StackArrayNode,*Stack;int IsEmpty(Stack S);int IsFull(Stack S);Stack CreatStack(int MaxStackSize);void FreeStack(Stack S);void Push(ElementType x, Stack S);void Pop(Stack S);ElementType Top(Stack S);ElementType TopandPop(Stack S);#endif

stack_array.c

IsEmpty(Stack S){if(S->TopOfStack == EmptyTOS)return TRUE;elsereturn FALSE;}int IsFull(Stack S){if(S->TopOfStack == S->Capacity)return TRUE;elsereturn FALSE;}Stack CreatStack(int MaxStackSize){Stack S;if(MaxStackSize < MinStackSize)printf(“Stack is too small\n”);S = (Stack)malloc(sizeof(struct StackArrayNode));if(S == NULL)exit(FALSE);S->Array = (ElementType *)malloc(sizeof(ElementType)*MaxStackSize);if(S->Array == NULL)exit(FALSE);S->Capacity = MaxStackSize;S->TopOfStack = EmptyTOS;}void FreeStack(Stack S){if(S != NULL){free(S->Array);free(S);}}void Push(ElementType x, Stack S){if(IsFull(S))printf(“Stack is full\n”);else{S->TopOfStack ++;S->Array[S->TopOfStack] = x;}}void Pop(Stack S){if(IsEmpty(S))printf(“Stack is empty\n”);else{S->TopOfStack –;}}ElementType Top(Stack S){if(!IsEmpty(S))return S->Array[S->TopOfStack];printf(“Stack is Empty\n”);return FALSE;}ElementType TopandPop(Stack S){if(!IsEmpty(S))return S->Array[S->TopOfStack–];printf(“Stack is Empty\n”);return FALSE;}int main(){Stack S;S = CreatStack(10);Push(1,S);Push(2,S);Push(4,S);printf(“%d\n”,Top(S));Pop(S);printf(“%d\n”,Top(S));Pop(S);printf(“%d\n”,Top(S));}链表栈的实现

stack.h

#ifndef _Stack_htypedef int ElementType;typedef struct StackNode{ElementType data;struct StackNode *next;}StackNode,*Stack;int isEmpty(Stack S);Stack CreateStack(void);void MakeEmpty(Stack S);void Push(ElementType x, Stack S);void Pop(Stack S);ElementType Top(Stack S);#endif /*_Stack_h */

stack.c

stdioint isEmpty(Stack S){if(S->next == NULL)return TRUE;;}void MakeEmpty(Stack S){if(S == NULL)printf(“fata error”);else{while(!isEmpty(S))Pop(S);}}Stack CreateStack(void){Stack S = (Stack)malloc(sizeof(struct StackNode));if(S == NULL)printf(“fata error”);S->next = NULL;MakeEmpty(S);return S;}void DeleteStack(Stack S){MakeEmpty(S);free(S);}void Push(ElementType x, Stack S){Stack TmpStack = (Stack)malloc(sizeof(struct StackNode));if(TmpStack == NULL)printf(“fata error”);else{TmpStackx;TmpStack->next = S->next;S->next = TmpStack;}}void Pop(Stack S){Stack TmpStack;if(isEmpty(S))printf(“Stack is Empty”);else{TmpStack = S->next;S->next = S->next->next;free(TmpStack);}}ElementType Top(Stack S){if(isEmpty(S))return FALSE;;}int main(){Stack S = CreateStack();Push(1,S);Push(2,S);Push(4,S);printf(“%d\n”,Top(S));Pop(S);printf(“%d\n”,Top(S));Pop(S);printf(“%d\n”,Top(S));}

参考自《数据结构与算法分析》

,思想如钻子,必须集中在一点钻下去才有力量

栈的C语言实现(链表和数组)

相关文章:

你感兴趣的文章:

标签云: