点击查看代码
//Doubly linked list
#include<iostream>
using namespace std;
struct node {
int data;
node* next;
node* prev;
};//定义双向链表结构体
node* A;
node* getnewnode(int x) {
node* temp = new node;
temp->data = x;
temp->prev = NULL;
temp->next = NULL;
return temp;
}//创建节点函数
void insertathead(int x) {
node* temp = getnewnode(x);
if (A == NULL) {
A = temp;
return;//不要忘记return//或者用else
}//头指针为空时
A->prev = temp;//1节点头部指向新节点
temp->next = A;//新节点尾巴指向1节点
A = temp;//头指针指向新节点//头指针与新节点不是双向,新节点头部默认指向NULL
}
void insertattail(int x) {
node* temp = getnewnode(x);
if (A == NULL) {
A = temp;
}
else {
node* run = A;
while (run->next != NULL) {
run = run->next;
}
run->next = temp;
temp->prev = run;//新节点头部指向末节点
}
}
void print() {
node* run = A;
while (run != NULL) {
cout << run->data<<" ";
run = run->next;
}
cout << endl;
}
void reverseprint() {
if (A == NULL) return;//empty list,exit
node* run = A;
while (run->next != NULL) {
run = run->next;
}//going to last node
while (run != NULL) {
cout << run->data << " ";
run = run->prev;
}//traversing backward uing prev pointer,结束时run指向NULL(run指向NULL:打印模式)
cout << endl;
}
int main() {
A = NULL;
insertathead(2); print(); reverseprint();
insertathead(4); print(); reverseprint();
insertathead(6); print(); reverseprint();
insertattail(-2); print(); reverseprint();
insertattail(-4); print(); reverseprint();
insertattail(-6); print(); reverseprint();
}