双向链表模拟栈的操作

手写双向链表模拟栈的:入栈、出栈、倒置操作。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <set>

using namespace std;
typedef long long LL;

#define E 2.71828
#define PI acos(-1.0)

vector<int>v;
char op[20];
int t,n,x;

struct node {
    node *pre;
    int x;
    node *next;
};

node *tail,*head;
int flag;

void push(int v) {
    node *p=new node ;

    if(!head)tail=p;

    if(flag==1) {

        p->pre=NULL;
        p->x=v;

        p->next=head;
        if(head)head->pre=p;

        head=p;
    }
    else if(flag==-1) {

        p->next=NULL;
        p->x=v;

        p->pre=head;
        head->next=p;

        head=p;
    }

}

void pop() {
    if(flag==1) {
        node *p=head->next;
        if(p)p->pre=NULL;

        delete head;
        head=p;
    }
    else if(flag==-1) {
        node *p=head->pre;
        if(p)p->next=NULL;

        delete head;
        head=p;
    }
}

void Reverse() {
    node *tmp=tail;
    tail=head;
    head=tmp;
    flag*=-1;
}

void print() {
    node *p=head;
    if(!p)cout<<"empty"<<endl;
    else {
    if(flag==1) {
        while(p) {
            cout<<p->x<<endl;
            p=p->next;
        }
    }
    else if(flag==-1) {
        while(p) {
            cout<<p->x<<endl;
            p=p->pre;
        }
    }
    }
    cout<<"--------------------------------"<<endl;
}

void init() {
    head=tail=NULL;
    flag=1;
}

int main () {
    ios::sync_with_stdio(false);
    init();
    cout<<"像向链表里插入3个元素1、2、3:"<<endl;
    push(1);
    push(2);
    push(3);
    print();
    cout<<"弹出栈顶元素:"<<head->x<<endl;
    pop();
    print();
    cout<<"弹出栈顶元素:"<<head->x<<endl;
    pop();
    print();
    cout<<"弹出栈顶元素:"<<head->x<<endl;
    pop();
    print();


    cout<<"像向链表里插入3个元素4、5、6:"<<endl;
    push(4);
    push(5);
    push(6);
    print();
    cout<<"执行倒置操作:"<<endl;
    Reverse();
    print();
    cout<<"像向链表里插入2个元素7、8:"<<endl;
    push(7);
    push(8);
    print();

    cout<<"使用循环,执行4次pop():"<<endl;
    for(int i=0;i<4;i++)
        pop();
    print();

    cout<<"执行倒置操作:"<<endl;
    Reverse();
    print();

    cout<<"像向链表里插入2个元素13、14:"<<endl;
    push(13);
    push(14);
    print();

    cout<<"执行倒置操作:"<<endl;
    Reverse();
    print();

    cout<<"使用循环,执行3次pop():"<<endl;
    for(int i=0;i<3;i++)
        pop();
    print();
    return 0;
}

结果展示:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水能zai舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值