带头节点的双向链表

与单链表相比,增加了指向前驱的指针,便于找到当前结点的前驱。

图源百度

初始化

 

typedef int datatype;
struct nodes{
    datatype data;
    struct nodes *last,*next;
};


struct List{
    struct nodes *head;
};

//创建头节点
void init(struct List *List){
    nodes *head=(nodes*)malloc(sizeof(nodes));
    head->next=NULL;
    head->last=NULL;
    List->head=head;
}

 

建立

头插法

连接1

连接2,3消失

连接4

连接5,6消失

//头插法
void createList(struct List *List){
    datatype num;
    cout<<"输入数据元素,当数据元素为-1时结束"<<endl;
    while(cin>>num&&num!=-1){
        nodes *temp=(nodes*)malloc(sizeof(nodes));
        temp->data=num;
        temp->next=(List->head)->next;
        (List->head)->next=temp;
        temp->last=List->head;
        if(temp->next!=NULL){
            (temp->next)->last=temp;
        }
    }
}

尾插法

连接1

连接2

连接3,4消失

更新tail

//尾插法
void createList(struct List *List){

    nodes *tail=List->head;
    datatype num;
    cout<<"输入数据元素,当数据元素为-1时结束输入"<<endl;
    while(cin>>num&&num!=-1){
        nodes *temp=(nodes*)malloc(sizeof(nodes));
        temp->data=num;
        temp->next=NULL;
        temp->last=tail;
        tail->next=temp;
        tail=temp;
    }
}

 打印链表

正序打印,倒序打印。

void print(struct List List){
    nodes *temp=List.head;
    while(temp->next!=NULL){
        temp=temp->next;
        cout<<temp->data<<"  ";
    }

    cout<<endl;

    while(temp!=List.head){
        cout<<temp->data<<"  ";
        temp=temp->last;
    }
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值