#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct List
{
int num;
struct List *next;
struct List *pre;
}List;
List *Insert_sort(List *head,int num)
{
List *tmp1 = head;
List *tmp0 = (List *)malloc(sizeof(List));
if(tmp0 == NULL)
return NULL;
tmp0->next = NULL;
tmp0->pre = NULL;
tmp0->num = num;
if(tmp1 == NULL)
{
head = tmp0;
return head;
}
while( (tmp0->num > tmp1->num) && (tmp1->next != NULL) )
{
tmp1 = tmp1->next;
}
if( tmp0->num <= tmp1->num )
{
if(head == tmp1)
{
tmp0->next = tmp1;
tmp1->pre = tmp0;
head = tmp0;
}
else
{
tmp0->next = tmp1;
tmp1->pre->next = tmp0;
tmp0->pre = tmp1->pre;
tmp1->pre = tmp0;
}
}
else
{
tmp1->next = tmp0;
tmp0->pre = tmp1;
tmp0->next = NULL;
}
return head;
}
List * Del_list(List *head,int num)
{
List *tmp1;
tmp1 = head;
while( num != tmp1->num && tmp1->next != NULL)
{
tmp1 = tmp1->next;
}
if(num == tmp1->num)
{
if(tmp1 == head)
{
head = head->next;
head->pre = NULL;
free(tmp1);
}
else if(tmp1->next == NULL)
{
tmp1->pre->next = NULL;
free(tmp1);
}
else
{
tmp1->next->pre = tmp1->pre;
tmp1->pre->next = tmp1->next;
free(tmp1);
}
}
else
{
printf("%d count not found\n",num);
}
return head;
}
void Print_list(List *head)
{
List * tmp = head;
while(tmp)
{
printf("%d ",tmp->num);
tmp = tmp->next;
}
printf("\n");
}
int main()
{
List *head_t = NULL;
for(int i=0;i<5;i++)
{
head_t = Insert_sort(head_t,i);
}
Print_list(head_t);
head_t = Del_list(head_t,3);
Print_list(head_t);
}
双向链表的插入与删除
最新推荐文章于 2024-04-24 19:23:34 发布