数据结构(C++)——链栈

结点结构

typedef char ElemType;

typedef struct LkStackNode{
    ElemType data;
    LkStackNode *next;
}*Stack,SNode,*PNode;

初始化链栈

Stack IntiStack(){
    Stack s;
    s=new LkStackNode;  //分配结点空间 
    s->next=NULL;         //处理next指针 
    
    return s;                  //返回栈指针 
}

压栈

bool Push(Stack S,ElemType &x){
    if(S==NULL){
        return false;   //栈无效,返回false 
    }
    
    PNode FirstCell;
    FirstCell=new SNode;  //为待数据分配一个结点空间 
    
    FirstCell->data=x;
    FirstCell->next=S->next;  //将新结点插在数据结点的最前面 
    S->next=FirstCell;
    
    return true;
}

出栈

bool Pop(Stack S,ElemType &x){
    if(S==NULL||S->next==NULL){   //栈无效或空栈,无法出栈,返回false 
        return false;
    }
    
    PNode FirstCell;
    
    FirstCell=S->next; 
    x=FirstCell->data;         //返回栈顶元素 
    
    S->next=FirstCell->next;
    delete FirstCell;          //释放栈顶空间 
    return true;
}

访问栈顶元素

bool Top(Stack S,ElemType &x){
    if(S==NULL||S->next==NULL){   //栈无效或空栈 
        return false;
    }
    
    x=S->next->data;
    
    return true; 
}
原文地址:https://www.cnblogs.com/WP-WangPin/p/12741928.html