双向链表,又称为双链表,是链表的一种,它的每个数据结点都有两个指针,分别指向直接后继和直接前驱。所以,双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。
基本操作:
#include
using namespace std;
class Node {
public:
int dat;
Node *pre;
Node *next;
Node(int val) {
dat = val;
pre = next = NULL;
}
};
class TList {
private:
Node *first;
Node *end;
public:
TList() { first = end = NULL; }
void append(int val);
void travalList() const;
void retravalList() const;
~TList() {
Node *p;
Node *t;
p = this->first;
while (p) {
t = p;
p = p->next;
delete t;
}
first = end = NULL;
}
};
// StudybarCommentEnd
void TList::append(int val) {
Node *temp = new Node(val);
if (this->first == NULL) {
this->first = temp;
this->end = temp;
} else if (this->first == this->end) {
this->first->next = temp;
temp->pre = this->first;
this->end = temp;
} else {
this->end->next = temp;
temp->pre = this->end;
this->end = temp;
}
}
void TList::travalList() const {
Node *temp = this->first;
while (temp) {
cout << temp->dat << " ";
temp = temp->next;
}
cout << endl;
}
void TList::retravalList() const {
Node *temp = this->end;
while (temp) {
cout << temp->dat << " ";
temp = temp->pre;
}
cout << endl;
}
int main(void) {
int a, b, c, d;
cin >> a >> b >> c >> d;
TList t;
t.append(a);
t.append(b);
t.append(c);
t.append(d);
t.travalList();
t.retravalList();
return 1;
}