#include<iostream>
using namespace std;
typedef struct student
{
int data;
student *pre;
student *next;
}dnode;
dnode* creat()
{
dnode *head, *p, *s;
head = new dnode;
p = head;
int cycle = 1;
int x;
while (cycle)
{
cout<<"Please input data : "<<endl;
cin>>x;
if (x)
{
s = new dnode;
s->data = x;
p->next = s;
s->pre = p;
p = s;
}
else
cycle = 0;
}
head = head->next;
head->pre = NULL;
p->next = NULL;
cout<<"The data of head is : "<<head->data<<endl;
return head;
}
int length(dnode* head)
{
dnode *p;
p = head;
int length_count = 0;
while (p)
{
p = p->next;
++length_count;
}
cout<<"The length of dlink is : "<<length_count<<endl;
return length_count;
}
dnode* print(dnode* head)
{
dnode *p;
p = head;
cout<<"The print result is: "<<endl;
while (p)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
return head;
}
dnode* delete_node(dnode* head, int num)
{
dnode *p, *q;
p = head;
int flag = 0;
if (NULL == p)
return head;
else
{
while (num == p->data)
{
q = p;
p = p->next;
head = p;
head->pre = NULL;
delete q;
}
p = p->next;
while (p)
{
if (num == p->data)
{
if (!flag)
flag = 1;
if (p->next)
{
q = p;
p = p->next;
p->pre = q->pre;
q->pre->next = p;
delete q;
}
else
{
q = p;
p = NULL;
q->pre->next = NULL;
delete q;
}
}
else
p = p->next;
}
if (!flag)
cout<<"There is no data you want to delete!"<<endl;
return head;
}
}
dnode* insert_node(dnode* head, int num)
{
dnode* p, *s;
p = head;
s = new dnode;
s->data = num;
while (s->data > p->data && NULL != p->next)
{
p = p->next;
}
if (s->data <= p->data)
{
if (head == p)
{
s->next = p;
p->pre = s;
head = s;
}
else
{
p->pre->next = s;
s->next = p;
s->pre = p->pre;
p->pre = s;
}
}
else
{
p->next = s;
s->pre = p;
s->next = NULL;
}
return head;
}
int main()
{
dnode* link_original = creat();
length(link_original);
print(link_original);
cout<<"Please input the num you want to delete: "<<endl;
int num;
cin>>num;
dnode* link_after_delete = delete_node(link_original, num);
print(link_after_delete);
cout<<"Please input the node you want to insert: "<<endl;
int input_num;
cin>>input_num;
dnode* result_after_insert = insert_node(link_after_delete, input_num);
print(result_after_insert);
}
双向链表(创建、求长、打印、删除、插入)
最新推荐文章于 2022-10-18 22:34:27 发布