栈链(c++实现)

  • Create_LinkStack(int size) 创建大小为size的栈链
  • Push_LinkStack(datatype x) 将x数据入栈
  • Pop_LinkStack() 将栈链顶部元素出栈

未加栈空判断,当前默认为栈不为空,主要体会数据交互过程

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_43477024/article/details/109630313