手写双向链表模拟栈的:入栈、出栈、倒置操作。
#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;
}
结果展示: