1. 程式人生 > >鏈式棧C++實現

鏈式棧C++實現

<span style="font-size:18px;">#include <iostream>
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

using namespace std;
typedef struct Node{
   int data;
   struct Node *pNext;
}NODE,*PNODE;

typedef struct Stack{
   PNODE pTop;
   PNODE pBottom;
}STACK,*PSTACK;
//函式宣告
void initStack(PSTACK);
void push(PSTACK,int);
void traverse(PSTACK);
bool pop(PSTACK,int *);
void clearStack(PSTACK);
bool empt(PSTACK);
int main(){
    STACK s;//STACK等價於struct Stack
    initStack(&s);
    push(&s,1);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    push(&s,5);
    push(&s,6);

    int val;
     traverse(&s);
    //出棧
    bool b = pop(&s,&val);
    if(b){
         //遍歷輸出
    printf("出棧成功,出棧元素=");
    printf("%d\n",val);
    traverse(&s);
    }else{
      printf("出棧失敗\n");
    }
    clearStack(&s);
    printf("清空棧\n");
    traverse(&s);
    printf("進棧\n");
    push(&s,1);
    push(&s,2);
    push(&s,3);
    traverse(&s);
    return 0;
}
//將棧清空
void clearStack(PSTACK pStack){
    if(empt(pStack)){
      return ;
    }else{
     while(pStack->pBottom!=pStack->pTop){
        PNODE p = pStack->pTop;
        pStack->pTop =p->pNext;
        free(p);
        p=NULL;

    }

    }
}
//用來判斷棧是否為空
bool empt(PSTACK pStack){
    if(pStack->pTop==pStack->pBottom){
        return true;
    }else{
        return false;
    }
}
//用來彈棧,這個val將出棧的元素儲存
bool pop(PSTACK pStack,int * val){
     if(empt(pStack)){
        return false;
     }else{
        PNODE p = pStack->pTop;
        pStack->pTop=p->pNext;
        *val =p->data;
        free(p);
        p=NULL;
        return true;
     }
}
//用來遍歷棧
void traverse(PSTACK pStack){
    PNODE p = pStack->pTop;
    while(p!=pStack->pBottom){
        printf("%d\n",p->data);
        p=p->pNext;
    }
}
//用來壓棧
void push(PSTACK pStack,int value){
    PNODE p = (PNODE)malloc(sizeof(NODE));
    if(NULL==p){
        printf("壓棧失敗\n");
        exit(-1);
    }else{
      p->data=value;
      p->pNext=pStack->pTop;//pStack->pTop不能隨便改成pStack->pBottom
      pStack->pTop=p;
    }
}
//用來初始化棧
void initStack(PSTACK pStack){
    PNODE p = (PNODE)malloc(sizeof(NODE));
    if(NULL==p){
        printf("動態記憶體分配失敗\n");
        exit(-1);
    }else{
        pStack->pBottom=p;
        pStack->pTop=p;
        pStack->pTop->pNext=NULL;
    }

}
</span>