双链表删除/插入节点

来源:互联网 发布:外文医学文献数据库 编辑:程序博客网 时间:2024/05/17 06:58
惊恐//双链表删除节点
dnode *del(dnode *head, int num)
{
dnode *p1, *p2;
p1 = head;
while (num != p1->data && p1->next != NULL)
{
p1 = p1->next;
}
if (num == p1->data)
{
if (p1 == head)
{
head = head->next;
head->pre = NULL;
free(p1);
}
else if (p1->next == NULL)
{
p1->pre->next = NULL;
free(p1);
}
else
{
p1->next->pre = p1->pre;
p1->pre->next = p1->next;
free(p1);
}
}
else
printf("\n %d could not been found", num);
return (head);

}

惊恐//双链表插入节点
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)
{
p1 = p1->next;
}
if (p0->data <= p1->data)
{
if (head == p1)
{
p0->next = p1;
p1->pre = p0;
head = p0;
}
else
{
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, stud;
int n, del_num, insert_num;
head = creat();
print(head);
cout << "\n Int:";
cin >> del_num;
head = del(head, del_num);
print(head);
cout << "\nplease input the insert data:";
cin >> insert_num;
head = insert(head, insert_num);
print(head);
return 0;
}

0 0
原创粉丝点击