/*分别用头尾插法构造单双向链表
*
*/
# include <iostream>
using namespace std;
class List{
public:
//单向链表节点
struct Node1
{
int data;
Node1* next;
};
//双向链表节点
struct Node2
{
int data;
Node2* prev;
Node2* next;
};
//单向链表尾插法
bool InsertBack1(int a, Node1*& head)
{
auto p = new Node1;
p->data = a;
if (head == NULL){
p->next = NULL;
} else {
p->next = head;
}
head = p;
return true;
}
//单向链表头插法
bool InsertFront1(int a, Node1*& head ,Node1*& tail)
{
auto p = new Node1;
p->data = a;
p->next = NULL;
if(head == NULL){
head = p;
}else{
tail->next = p;
}
tail = p;
return true;
}
//双向链表尾插法
bool InsertBack2(int a, Node2*& head, Node2*& tail)
{
auto p = new Node2;
p->data = a;
if (head == NULL){
tail = p;
p->next = NULL;
head = p;
tail->prev = NULL;
} else {
p->next = head;
head->prev = p;
p->prev = NULL;
head = p;
}
return true;
}
//双向链表头插法
bool InsertFront2(int a, Node2*& head, Node2*& tail)
{
auto p = new Node2;
p->data = a;
if(head == NULL)
{
head = p;
tail = p;
head->prev = NULL;
tail->next = NULL;
}
else
{
tail->next = p;
p->prev = tail;
tail = p;
}
}
//查看单向链表
void show1(Node1* head)
{
auto p = head;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//查看单向链表
void show2(Node2* head)
{
auto p = head;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//从尾向前查看双向链表
void show(Node2* tail)
{
auto p = tail;
while (p != NULL){
cout << p->data << " ";
p = p->prev;
}
cout << endl;
}
};
int main()
{
List l;
List::Node1* head1 = NULL;
List::Node1* head2 = NULL;
List::Node1* tail = NULL;
l.InsertBack1 (5,head1);
l.InsertBack1 (6,head1);
l.InsertBack1 (7,head1);
l.InsertBack1 (8,head1);
l.InsertBack1 (9,head1);
cout << "尾插法构造单向链表 " << endl;
l.show1(head1);
l.InsertFront1 (5,head2,tail);
l.InsertFront1 (6,head2,tail);
l.InsertFront1 (7,head2,tail);
l.InsertFront1 (8,head2,tail);
l.InsertFront1 (9,head2,tail);
cout << "头插法构造单向链表 " << endl;
l.show1(head2);
List::Node2* head3 = NULL;
List::Node2* tail3 = NULL;
List::Node2* head4 = NULL;
List::Node2* tail4 = NULL;
l.InsertBack2 (11,head3,tail3);
l.InsertBack2 (12,head3,tail3);
l.InsertBack2 (13,head3,tail3);
l.InsertBack2 (14,head3,tail3);
l.InsertBack2 (15,head3,tail3);
cout << "头插法构造双向链表 " << endl;
l.show2(head3);
cout << "头插法构造双向链表(从尾向前查看)" << endl;
l.show(tail3);
l.InsertFront2 (11,head4,tail4);
l.InsertFront2 (12,head4,tail4);
l.InsertFront2 (13,head4,tail4);
l.InsertFront2 (14,head4,tail4);
l.InsertFront2 (15,head4,tail4);
cout << "尾插法构造双向链表 " << endl;
l.show2(head4);
cout << "尾插法构造双向链表(从尾向前查看)" << endl;
l.show(tail4);
}