#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
typedef int Type;
typedef struct DoubleList
{
Type num;
struct DoubleList *pre;
struct DoubleList *next;
}DList;
DList *Head = NULL;
int Head_Init()
{
Head = (DList *)malloc(sizeof(DList));
if(Head == NULL)
{
perror("malloc fail\n");
return -1;
}
Head->pre = NULL;
Head->next = NULL;
return 0;
}
void DList_Add(Type add_num)
{
DList *new = (DList *)malloc(sizeof(DList));
if(new == NULL)
{
perror("malloc fail\n");
return ;
}
new->num = add_num;
if(Head->next == NULL)
{
Head->next = new;
new->pre = Head;
new->next = NULL;
}
else
{
new->next = Head->next;
Head->next->pre = new;
Head->next = new;
new->pre = Head;
}
}
void DList_Display()
{
int i = 0;
DList *p = Head->next;
printf("\n*******************\n");
while(p != NULL)
{
printf("[%d] : %d\n", i++, p->num);
p = p->next;
}
printf("\n*******************\n");
}
void DList_Delete(Type del_num)
{
int flag = 0;
DList *p = Head->next;
DList *tmp = NULL;
while(p != NULL)
{
if(p->num == del_num)
{
flag = 1;
tmp = p;
p = p->next;
if(tmp->next == NULL)
{
tmp->pre->next = NULL;
tmp->pre = NULL;
free(tmp);
tmp = NULL;
}
else
{
tmp->pre->next = tmp->next;
tmp->next->pre = tmp->pre;
tmp->pre = NULL;
tmp->next = NULL;
free(tmp);
tmp = NULL;
}
continue;
}
p = p->next;
}
if(flag == 1)
{
printf("\ndelete %d success\n", del_num);
}
else
{
printf("\n%d does not exist\n", del_num);
}
}
void DList_Destroy()
{
DList *p = Head->next;
while(p->next != NULL)
{
p->next->pre = Head;
Head->next = p->next;
p->pre = NULL;
p->next = NULL;
free(p);
p = Head->next;
}
Head->next = NULL;
Head->pre = NULL;
p->pre = NULL;
p->next = NULL;
free(p);
p = NULL;
printf("\n***********Destroy success*********\n");
}
void DList_Change(Type old_num, Type new_num)
{
DList *p = Head->next;
while(p != NULL)
{
if(p->num == old_num)
{
p->num = new_num;
}
p = p->next;
}
}
int main(void)
{
if(Head_Init() != 0)
{
printf("Head init fail\n");
return -1;
}
int choose = 0;
while(1)
{
printf("\n1.Add 2.Display 3.Exit 4.Change 5.Delete 6.Destroy\n");
fscanf(stdin, "%d", &choose);
switch(choose)
{
case 1:
{
printf("input : ");
int num;
fscanf(stdin, "%d", &num);
DList_Add(num);
break;
}
case 2:
{
DList_Display();
break;
}
case 3:
{
printf("\n***********exit**************\n");
return -1;
}
case 4:
{
printf("\nwhich num change to which num\n");
int old_num, new_num;
fscanf(stdin, "%d %d", &old_num, &new_num);
DList_Change(old_num, new_num);
break;
}
case 5:
{
printf("\ndelete which num\n");
int del_num;
fscanf(stdin, "%d", &del_num);
DList_Delete(del_num);
break;
}
case 6:
{
DList_Destroy();
break;
}
default:
{
printf("\nDo not have the chose\n");
break;
}
}
}
return -1;
}
这是本人整理对于双链表的代码,如发现有不对之处,还请指出!!