链表(三)双向链表

1.概念
双向链表(Double Linked List)的节点有两个指针,一个指向直接前驱,一个指向直接后继。
2.优点
查找直接前驱执行时间为O(1),单链表为O(n).
3.存储结构

//双向链表
typedef struct DuLNode{

 int data;  //数据域
 struct DuLNode *prior; //前驱
 struct DuLNode *next;  //后继

}DuLNode,*DuLinkList;

4.简单实例

#include <iostream>
#include <string.h>
using namespace std;
//双向链表
typedef struct DuLNode{

 int data;
 struct DuLNode *prior;
 struct DuLNode *next;

}DuLNode,*DuLinkList;

void InitList(DuLinkList &L)
{
    L=new DuLNode;
    L->data = 0;
    L->prior = NULL;
    L->next = NULL;
}

void add(DuLinkList L,int d)
{
    while(L->next!=NULL)
    {
        L=L->next;
    }
    DuLNode *n=new DuLNode;
    n->data=d;
    n->next=NULL;
    n->prior=L;
    L->next=n;
}

void display(DuLinkList L)
{
    DuLNode *p=NULL;
    p=L->next;
    while(p!=NULL)
    {
       cout<<p->prior->data<<"<=前驱="<<p->data<<"=后继=>"<<p->next->data<<endl;
       p=p->next;
    }
}
void newlist(DuLinkList L)
{
    int n=1;
    while(n)
    {
    int t;
    cout<<"InPut.";cin>>t;
    add(L,t);
    cout<<" Do you want new a node[1/0] agin?"<<endl;
    cin>>n;
    }
}
int main()
{
    DuLinkList L;
    InitList(L);
    newlist(L);
    display(L);
}

5.运行效果

注 : 最后一个节点6无直接后继。
6.补充
类似单链的循环表,双向链表也有循环表,如下图

posted @ 2021-01-28 22:21  HUGBOY  阅读(413)  评论(0编辑  收藏  举报