倒置单项链表接口实现

前端之家收集整理的这篇文章主要介绍了倒置单项链表接口实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

分别用递归和非递归方式实现

/*
*非递归实现
*@retval:NULL on fail,else on success
*/
link_t *link_reverse(link_t *head)
{
	link_t *cur = head;
	link_t *cur_r;
	link_t *cur_l = NULL;
	
	while( cur != NULL )
	{
		cur_r = cur->next;
		cur->next = cur_l;
		cur_l = cur;
		cur = cur_r;	
	}
	
	return cur_l;
}

link_t *link_reverse_r0(link_t *head,link_t **new_head)
{	
	assert( head != NULL );
	
	if( head->next == NULL )
	{
		*new_head = head;
		return head;
	}
	else
	{
		link_t *p = link_reverse_r0( head->next,new_head);
		p->next = head;
		return head;
	}
}

/*
*递归实现
*/
link_t *link_reverse_r(link_t *head)
{
	link_t *new_tail = head;
	link_t *new_head = NULL;
	link_reverse_r0(head,&new_head);
	new_tail->next = NULL;
	
	return new_head;	
}
原文链接:https://www.f2er.com/javaschema/285097.html

猜你在找的设计模式相关文章