#include<iostream>
using namespace std;
struct node {
int val;
node* pre;
node* next;
node(int v,node*p,node* nxt):val(v),pre(p),next(nxt){}
};
node* head = nullptr;
node* tail = nullptr;
void printlist() {
node* p = head;
while (p != nullptr) {
cout << p->val << " ";
p = p->next;
}
}
void printlist2() {
node* p = tail;
while (p != nullptr)
{
cout << p->val << " ";
p = p->pre;
}
}
void push_back(int val)
{
node* p = new node(val, nullptr, nullptr);
tail->next = p;
p->pre = tail;
tail = p;
}
void push_front(int val)
{
node* p = new node(val, nullptr, nullptr);
p->next = head;
head->pre = p;
head = p;
}
void pop_front()
{
node* tmp = head;
head = head->next;
delete tmp;
}
void pop_back()
{
node* tmp = tail;
tail = tail->pre;
tail->next = nullptr;
delete tmp;
}
int main() {
int n, x; cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> x;
node* p = new node(x, nullptr, nullptr);
if (head == nullptr) head = p;
else {
tail->next = p;
p->pre = tail;
}
tail = p;
}
printlist();
cout << endl;
printlist2();
cout << endl;
push_front(0);
push_back(10);
printlist();
cout << endl;
printlist2();
return 0;
}
双链表及其基本操作(底层)
最新推荐文章于 2024-08-30 15:37:42 发布