C++数据结构 11 双向链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014183456/article/details/83147332

双向链表:

有三个域:

  1. 左链域 llink
  2. 右链域 rlink
  3. 数据域 data

需要有表头结构


#ifndef __DoubleList_H__
#define __DoubleList_H__

#include <iostream>

using namespace std;

class DoubleList;  //声明

class DoubleListNode   //节点
{
   friend class DoubleList;
public:
    int data;
    DoubleListNode *llink,*rlink;
};

class DoubleList
{
public:
    DoubleList()
    {
      first=new DoubleListNode();
      first->llink=first->rlink=first;    //first的左边和右边都指向自己
    }
    void Insert(DoubleListNode*p,DoubleListNode*x);  //插入 向数据的右边插入
    void Delet(DoubleListNode*);  //删除数据
//private:
    DoubleListNode* first;  //指向第一个数据
};

void DoubleList::Insert(DoubleListNode*p,DoubleListNode*x)//将p插入到x的右边
{
   p->llink=x;
   p->rlink=x->rlink;
   x->rlink->llink=p;
   x->rlink=p;
}

void DoubleList::Delet(DoubleListNode*x)  //删除一个元素
{
    if(x==first) cout<<"Error";
    else
    {
        x->llink->rlink=x->rlink;
        x->rlink->llink=x->llink;
    }
}

#endif // __DoubleList_H__

main

#include <iostream>
#include "DoubleList.h"
using namespace std;

int main()
{
    DoubleList P;
    DoubleListNode node1,node2,node3,node4,node5;
    node1.data=10;
    node2.data=20;
    node3.data=30;
    node4.data=40;
    node5.data=50;
    P.Insert(&node1,P.first);
    P.Insert(&node2,P.first);
    P.Insert(&node3,P.first);
    P.Insert(&node4,P.first);
    P.Insert(&node5,P.first);
    cout<<P.first->rlink->data<<endl;
    cout<<P.first->rlink->rlink->data<<endl;
    cout<<P.first->rlink->rlink->rlink->data<<endl;
    cout<<P.first->rlink->rlink->rlink->data<<endl;
    cout<<P.first->rlink->rlink->rlink->rlink->data<<endl;
    P.Delet(&node3);
    cout<<P.first->rlink->data<<endl;
    cout<<P.first->rlink->rlink->data<<endl;
    cout<<P.first->rlink->rlink->rlink->data<<endl;
    cout<<P.first->rlink->rlink->rlink->data<<endl;
    cout<<P.first->rlink->rlink->rlink->rlink->data<<endl;
   // cout << "Hello world!" << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014183456/article/details/83147332