c实现出栈入栈功能

1  原理图

c实现出栈入栈功能_第1张图片

2 最后的效果图

c实现出栈入栈功能_第2张图片


3 完整代码如下:


#include<stdio.h>
#include<malloc.h>

typedef  struct Node{
  int data;
  struct Node  * pNext;
}Node,*PNode;

typedef struct Stack{
  PNode pbottom;
  PNode ptop;
}Stack,*PStack;

PStack initStack();
int isEmpty(PStack pStack);
void pushStack(PStack pStack,int val);
void traverseStack(PStack pStack);
void popStack(PStack pStack);

int main(void){
 //初始化栈
 PStack pStack;
 pStack = initStack();
 //入栈
 if(isEmpty(pStack)){
    printf("栈为空1\n");
 }
 pushStack(pStack,1);
 pushStack(pStack,2);
 pushStack(pStack,3);
 pushStack(pStack,4);
 pushStack(pStack,5);
 pushStack(pStack,6);
 pushStack(pStack,7);
 pushStack(pStack,8);
  if(isEmpty(pStack)){
    printf("栈为空2\n");
 }
 //遍历栈
 traverseStack(pStack);
 //出栈
 popStack(pStack);
 //遍历栈
 traverseStack(pStack);
  //出栈
 popStack(pStack);
 //遍历栈
 traverseStack(pStack);
 return 1;
}

int isEmpty(PStack pStack){
   if(pStack->ptop->pNext == NULL){
    return 1;
   }else{
    return 0;
   }
};

//遍历栈
void traverseStack(PStack pStack){
 if(isEmpty(pStack)){
    printf("栈为空");
    exit(1);
  }
  PNode pnode =  pStack->ptop;
  // pStack->ptop
  printf("栈的值为: \n");
   while(pnode->pNext!= NULL){
     printf("%d ",pnode->data);
     pnode = pnode->pNext;
   }
  printf("\n");
}

//出栈
void popStack(PStack pStack){
  if(isEmpty(pStack)){
    printf("出栈失败,栈为空");
    return ;
  }
  if(pStack->ptop->pNext != NULL){
     PNode pnode =  pStack->ptop;
     printf("出栈元素的值为 : %d\n",pnode->data);
     pStack->ptop = pStack->ptop->pNext;
     free(pnode);
     //销毁无用的Node

   }

}

//入栈
void pushStack(PStack pStack,int val){
    //初始化节点
    PNode node = (Node *) malloc(sizeof(Node));
    if(node==NULL){
        printf("入栈失败,内存内存不够");
        exit(1);
    }

    node->data = val;
    node->pNext = pStack->ptop;
   //入栈 PNode node = NULL;
    pStack->ptop = node;


};

//初始化栈
PStack initStack(){
  printf("初始化栈\n");
  PStack pStack = (Stack *)malloc(sizeof(Stack));
  if(pStack==NULL){
    printf("初始化栈失败,内存不够");
    exit(1);
  }
  pStack->ptop = (Node *)malloc(sizeof(Node));
  pStack->ptop->pNext = NULL;
  pStack->pbottom = pStack->ptop ;
  return pStack;

}


你可能感兴趣的:(c实现出栈入栈功能)