Stack

1.顺序表实现栈

#include<iostream>
#define MaxSize 50
using namespace std;
int push(int a[],int &top){
    if(top==MaxSize){
        return 0;
    }
    int value;
    cin>>value;
    a[++top]=value;
    return 1;
}
int pop(int a[],int &top){
    if(top==-1){
        return 0;
    }
    return a[top--];
} 
int main(){
    int stack[MaxSize];
    int top=-1;
    for(int i=0;i<6;i++){
        push(stack,top);
    }
    while(top!=-1){
        cout<<pop(stack,top)<<' ';
    }
}

2.单链表实现栈

#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct LNode{
    int data;
    struct LNode *next;
}LNode;
void push(LNode *head,LNode *&top){
    top=(LNode*)malloc(sizeof(LNode));
    cin>>top->data;
    top->next=head->next;
    head->next=top;
}
int pop(LNode *head,LNode *&top){
    if(head->next==NULL){
        return 0;
    }
    int x=top->data;
    head->next=top->next;
    free(top);
    top=head->next;
    return x;
}
int main(){
    LNode *head=(LNode*)malloc(sizeof(LNode));
    head->next=NULL;
    LNode *top=NULL;
    for(int i=0;i<6;i++){
        push(head,top);
    }
    LNode *temp=head->next;
    while(temp!=NULL){
        cout<<temp->data<<' ';
        temp=temp->next;
    }
    cout<<endl<<pop(head,top);
    return 0;
}

 

posted on 2020-06-22 13:35  二进制dd  阅读(195)  评论(0编辑  收藏  举报

导航