Stack chain (c++ implementation)

  • Create_LinkStack(int size) Create a stack chain of size size
  • Push_LinkStack(datatype x) Push x data into the stack
  • Pop_LinkStack() pops the top element of the stack chain

No stack empty judgment, the current default is that the stack is not empty, mainly to experience the data interaction process

#include<bits/stdc++.h>
using namespace std;
typedef int datatype;

class Node{
    
             //节点类
    public:
        datatype data;
        Node *next;
};

class LinkStack{
    
    
    public:
        LinkStack();
        ~LinkStack();
        void Create_LinkStack(int size);
        void Push_LinkStack(datatype x);
        datatype Pop_LinkStack();
        Node *head;
        int top;
        int size;
};

LinkStack::LinkStack(){
    
    
    head=new Node;
    head->data=0;
    head->next=NULL;
    this->top=-1;
}

LinkStack::~LinkStack(){
    
    
    delete head;
}

void LinkStack::Create_LinkStack(int size){
    
    
    Node *ptemp;
    Node *ptemp2;
    this->size=size;
    for(int i=0;i<size;++i){
    
    
        cin>>ptemp->data;
        ptemp2=this->head->next;
        this->head->next=ptemp;
        ptemp->next=ptemp2;
    }
}

void LinkStack::Push_LinkStack(datatype x){
    
    
    Node *pnew;
    Node *ptemp;
    pnew->data=x;
    ptemp=this->head->next;
    this->head->next=pnew;
    pnew->next=ptemp;
}

datatype LinkStack::Pop_LinkStack(){
    
    
    Node *ptemp;
    ptemp=this->head->next;
    this->head->next=ptemp->next;
    datatype x=ptemp->data;
    free(ptemp);
    return x;
}

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/109630313