分别用头尾插法构造单双向链表.cpp

/*分别用头尾插法构造单双向链表
 *
 */
# 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);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值