现在的位置: 首页 > 综合 > 正文

24 单链表就地逆置,合并链表

2018年01月20日 ⁄ 综合 ⁄ 共 658字 ⁄ 字号 评论关闭
/*
第 24  题:
链表操作,
(1).单链表就地逆置,
(2)合并链表
*/


node * reverseNonrecurse(node *head)
{
	if(head==NULL) return head;
	
	node *p=head,*previous=NULL,*next=NULL;
	
	while(p->next!=NULL)
	{
		next=p->next;//保存下一个 
		p->next=previous;//p下一个为他前面的
		previous=p;
		p=next; 
	}
	p->next=previous;
	return p;
}

//两个排好序的合并 
Node *merge(Node *h1, Node *h2) 
{
	if (h1==NULL) return h2;
	if (h2==NULL) return h1;
	Node *head;
	if (h1->data>h2->data) //谁做头 
	{
		head=h2;
		h2=h2->next;
	} 
	else 
	{
		head=h1;
		h1=h1->next;
	}
	
	Node *current=head;
	
	while(h1!=NULL||h2!=NULL) 
	{
		if(h1==NULL || (h2!=NULL&&h2->data<h1->data))//h1空,或者h2不为空,并且值小于h1 
		{
			current->next=h2;
			h2=h2->next; 
			current=current->next;
		} 
		else 
		{
			current->next=h1;
			h1=h1->next;
			current=current->next;
		} 
	}
	current->next = NULL;
	return head; 
}

抱歉!评论已关闭.