您的位置:首页 > 编程语言 > C语言/C++

双链表的建立,测长度,打印,插入c++代码实例及运行结果

2018-02-03 11:36 585 查看
跟单链表类似操作类似点击打开链接

c++代码

#include <iostream>

using namespace std;

typedef struct st
{
int data;
struct st *pre;
struct st *next;
}dNode;

//双链表的建立
dNode *create()
{
dNode *head,*p,*s;
int x,cycle=1;

head=(dNode*)malloc(sizeof(dNode));
p=head;
while(cycle)
{
cout<<"请依次输入双链表的元素x"<<endl;
cin>>x;
if(x!=0)//输入0结束输入
{
s=(dNode*)malloc(sizeof(dNode));
s->data=x;
p->next=s;
s->pre=p;
p=s;
}
else
cycle=0;
}
head=head->next;
head->pre=NULL;
p->next=NULL;

return head;
}

//双链表的长度
int length(dNode *head)
{
int n=0;
dNode *p;
p=head;
while(p!=NULL)
{
p=p->next;
n++;
}
return n;
}

//双链表的打印
void print(dNode *head)
{
dNode *p;
p=head;
if(head!=NULL)
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}

//双链表的插入
dNode *insert(dNode *head,int num)
{
dNode *p0,*p1;
p1=head;
p0=(dNode*)malloc(sizeof(dNode));
p0->data=num;
while(p0->data>p1->data&&p1->next!=NULL)//插入条件p0->data<=p1->data
{
p1=p1->next;
}
if(p0->data<=p1->data)
{
if(head==p1)//头结点插入
{
p0->next=p1;
p1->pre=p0;
head=p0;
}
else//p1前插入p0
{
p1->pre->next=p0;
p0->next=p1;
p0->pre=p1->pre;
p1->pre=p0;
}
}
else//尾节点插入
{
p1->next=p0;
p0->pre=p1;
p0->next=NULL;
}
return head;
}

int main()
{
dNode *head;
int insert_num,del_num;
int len;
head=create();
len=length(head);
cout<<"双链表的长度为"<<len<<endl;
print(head);

cout<<"请输入插入的元素x"<<endl;
cin>>insert_num;
head=insert(head,insert_num);
len=length(head);
cout<<"双链表的长度为"<<len<<endl;
print(head);

return 0;
}

运行结果

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