<span style="font-size:18px;">#include<iostream>
using namespace std;
typedef struct DNode
{
int data;
DNode *left;
DNode *right;
};
//建立双向链表
DNode*creatlist(int num)
{
DNode *head,*p;
head=(DNode*)malloc(sizeof(DNode));
head->left=head;
head->right=head;
p=head;
for(int i=0;i<num;i++)
{
cout<<"请输入节点的数据:"<<endl;
int data;
cin>>data;
DNode *q=(DNode*)malloc(sizeof(DNode));
q->data=data;
p->right=q;
q->left=p;
p->left=q;
q->right=head;
p=q;
}
return head;
}
//打印双向链表
void printlist(DNode*head)
{
DNode*p=head->right;
while(p!=head)
{
cout<<p->data<<endl;
p=p->right;
}
}
//测量双向链表的长度
int listlength(DNode*head)
{
int count(1);
DNode*p=head->right;
while(p!=head)
{
//cout<<p->data<<endl;
p=p->right;
count++;
}
return count;
}
//双向链表节点的查找
DNode*SearchNode(DNode*head,int data)
{
DNode*p=head->right;
while(p->right!=head&&p->data!=data)
{
p=p->right;
}
return p;
}
int main()
{
cout<<"创建双向链表:"<<endl;
cout<<"请输入双向链表的长度:";
int num;
cin>>num;
DNode*head=creatlist(num);
printlist(head);
cout<<"链表的长度:";
cout<< listlength(head)<<endl;
cout<<"输入查找节点的数据:";
int data;
cin>>data;
DNode*Pnode=SearchNode(head, data);
cout<<Pnode->data<<endl;
return 0;
}</span>
双向链表的基本操作
最新推荐文章于 2023-11-10 12:58:42 发布