双向链表的简单实现

一、简单说说链表概念

链表和数组在逻辑上讲都属于线性表,只是在物理上他们的存储方式不一样。怎么个不一样就不废话了,但是总结一条,这种存储方式的不同使得数组便于随机存取,而链表在删除和插入方面效率要比数组高。

二、代码实现:(操作指针是要保持头脑清醒,时刻注意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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值