您的位置:首页 > 其它

双向链表的生成,删除,插入

2016-10-10 17:47 176 查看

双向链表的生成,删除,插入

#include<iostream>

#include<stdlib.h>

struct s

{

    int a;

    struct s *next;

    struct s *prior;

};

int main()

{

    struct s*head,*p,*q,*j,*s,*k;/*head为头结点,q为开头尾节点 创建链表时使用,j为遍历列表 读取数据时使用,s为最终尾节点,

    k为要删除的节点*/

    head=(struct s * )malloc(sizeof(struct s));

    head->a=11;

    head->next=NULL;//创建头结点

    s=q=(struct s * )malloc(sizeof(struct s));

    q->a=12;

    q->next=NULL;//创建尾节点

    q->prior=head;

    head->next=q;//连接头结点和尾节点

    for(int i=0;i<10;i++)

    {

        p=(struct s * )malloc(sizeof(struct s));

        p->a=i;

        //创建中间节点

        p->prior=head;

        q->prior->next=p;

        p->next=q;

        q->prior=p;

        q=q->prior;//插入的过程,插入先连前边的节点再连后边的节点

    }

    j=head;

    while(j!=NULL)

    {

        std::cout<<j->a<<" ";

        j=j->next;

    }//由头到尾正序输出

     std::cout<<std::endl;

    j=s;

    while(j!=NULL)

    {

        std::cout<<j->a<<" ";

        j=j->prior;

    }//由尾到头逆序输出

    std::cout<<std::endl;

    s->next=head;

    head->prior=s;

    //循环双向链表

    j=head;

    for(int i=0;i<20;i++)

    {

        std::cout<<j->a<<" ";

        j=j->next;

    }

    std::cout<<std::endl;

    //循环双向链表的输出

    k=head->next->next;

    k->prior->next=k->next;

    k->next->prior=k->prior;

    //循环链表的删除

    std::cout<<k->a<<" ";

     std::cout<<std::endl;

    j=head;

    for(int m=0;m<20;m++)

    {

        std::cout<<j->a<<" ";

        j=j->next;

    }

    free(k);//释放节点

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: