一、简单说说链表概念
链表和数组在逻辑上讲都属于线性表,只是在物理上他们的存储方式不一样。怎么个不一样就不废话了,但是总结一条,这种存储方式的不同使得数组便于随机存取,而链表在删除和插入方面效率要比数组高。
二、代码实现:(操作指针是要保持头脑清醒,时刻注意NULL,你懂得,哈哈)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DATA_SIZE 10
typedef struct DLinkList
{
int data;
struct DLinkList *prev;
struct DLinkList *next;
}DLinkList;
DLinkList* create_list(int size);
void print_list(DLinkList *h);
void free_list(DLinkList *h);
void del_data(DLinkList *h, int data);
void insert_data(DLinkList *h, int elem, int data);
int main()
{
DLinkList *head = create_list(DATA_SIZE);
if (NULL == head)
{
return -1;
}
puts("Init Link List:");
print_list(head);
printf("Input the data you want to delete:");
int data;
scanf("%d", &data);
del_data(head, data);
puts("After delete data, list is :");
print_list(head);
int elem;
printf("Insert after whice elem:");
scanf("%d", &elem);
printf("Input the data you want to insert:");
scanf("%d", &data);
insert_data(head, elem, data);
puts("After insert data, list is:");
print_list(head);
free_list(head);
return 0;
}
DLinkList* create_list(int size)
{
DLinkList *head;
head = (DLinkList*)malloc(sizeof(DLinkList));
if (NULL == head)
{
return NULL;
}
head->data = size;
head->prev = NULL;
head->next = NULL;
DLinkList *cur = head;
int i;
srand(time(NULL));
for (i = 0 ; i < size ; ++i)
{
DLinkList *elem = (DLinkList*)malloc(sizeof(DLinkList));
if (NULL == elem)
{
break;
}
elem->data = rand()%100;
elem->prev = cur;
elem->next = NULL;
cur->next = elem;
cur = elem;
}
return head;
}
void print_list(DLinkList *h)
{
DLinkList *cur = h->next;
while (cur)
{
printf("%4d", cur->data);
cur = cur->next;
}
printf("\n");
}
void free_list(DLinkList *h)
{
DLinkList *cur = h;
while (cur)
{
DLinkList *tmp = cur->next;
free(cur);
cur = tmp;
}
}
void del_data(DLinkList *h, int data)
{
DLinkList *cur = h->next;
while (cur)
{
if (cur->data == data)
{
break;
}
cur = cur->next;
}
if (NULL == cur)
{
printf("Cannot find %d.\n", data);
return;
}
cur->prev->next = cur->next;
if (cur->next != NULL)
{
cur->next->prev = cur->prev;
}
free(cur);
cur = NULL;
}
void insert_data(DLinkList *h, int elem, int data)
{
DLinkList *cur = h->next;
while (cur)
{
if (cur->data == elem)
{
break;
}
cur = cur->next;
}
if (NULL == cur)
{
printf("Cannot find %d.\n", elem);
return;
}
DLinkList *tmp = (DLinkList*)malloc(sizeof(DLinkList));
if (NULL == tmp)
{
puts("Insert error because of malloc error");
return;
}
tmp->data = data;
tmp->next = cur->next;
if (tmp->next != NULL)
{
tmp->next->prev = tmp;
}
tmp->prev = cur;
cur->next = tmp;
}