双向链表的实现1

这里介绍链表的打印输出,链表的反向和链表销毁。

1)正向打印出所有的节点:

int print_lst(list *head)
{
	if (head == NULL)
	{
		perror("head is null !\n");
		return -1;
	}

	list *p;
	int count;

	for(p = head, count = 0; p != NULL; ++ count)
	{
		if (count != 0 && (count % 5)  == 0)
			printf("\n");

		printf ("%d\t", *((int *)(p->p_data)));
		p = p->next;
	}
	
	printf("\n");

	return 0;
}

2)反向打印所有的结点:

int print_lst_from_tail(list *head)
{
	printf("print out the list from tail!\n");
	
	if (head == NULL)
	{
		perror(" head is null !\n");
		return -1;
	}

	list *p, *tail;
	int count;
	
	for (p = head; p->next != NULL; p = p->next)
		;

	tail = p;

	for(p = tail, count = 0; p != NULL; ++ count)
	{
		if (count != 0 && (count % 5)  == 0)
			printf("\n");

		printf ("%d\t", *((int *)(p->p_data)));
		p = p->pre;
	}
	
	printf("\n");

	return 0;
}

3)对链表所有的元素反向:

int reverse_lst(list **hd)
{
	printf("%s!\n", __func__);
	list *head = *hd;
	
	if (head == NULL)
	{
		perror("invalid list!\n");	
		return -1;
	}

	list *p, *q, *r, *tail;
		
	for (r = head; r->next != NULL; r = r->next)
		;

	tail = r;
	for (p = tail; p != NULL; )
	{
		q = p;
		p = p->pre;
		
		r->next = q;
		q->pre = r;
		q->next = NULL;
		r = q;
	}	

	tail->pre = NULL;
	*hd = tail;

	return 0;
}


4)销毁:

int free_lst(list *lst)
{
	if (lst == NULL)
		return -1;

	list *p, *q;
	for (p = lst; p->next != NULL; )
	{
		q = p;

		if (p->next != NULL)
		{
			if (q->p_data != NULL)
				free(q->p_data);
			
			free(q);
			p = p->next;	
		}
		else
		{
			if (p->p_data != NULL)
				free (p->p_data);

			free(p);
		}
	}

	return 0;
}

下一篇介绍链表的冒泡排序。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值