c++实现两有序链表合并成一个新链表

 
  
struct Node
{
	int x;
	Node * next;
	Node(int x1,Node * next1)
	{
		x = x1;
		next = next1;
	}
};

//--两个有序链表合并-假设排列方式为从小到大--
Node * sortHead(Node * head1,Node * head2)
{
	if(head1 == nullptr) return head2; if(head2 == nullptr) return head1;
	Node * returnHead = head1->xx?head1:head2; //新链表的头节点(里面的是三目运算符..)
	Node * MyPos = returnHead;// 标记新链表的最后一个位置
	if(head1->x < head2->x)
		head1 = head1->next;
	else
		head2 = head2->next;
	while(1)
	{
		if(head1 == nullptr)
		{
			MyPos->next = head2; // head1 都被加载完后另,新链表的最后一个位置与head2串联起来
			break;
		}else if(head2 == nullptr)
		{
			MyPos->next = head1;// 同理--
			break;
		}
		if(head1->xx)
		{
			MyPos->next = head1;//代码1
			MyPos = head1;//代码2 --作用将目前head1和head2里最小的那个节点放到新链表的最后一个节点-并重新标记新的节点
			head1 = head1->next;
		}else
		{
			MyPos->next = head2;
			MyPos = head2;
			head2 = head2->next;
		}
	}

	return returnHead;
}


 
  
 
  

 
  
 
  
 
  
 
 

你可能感兴趣的:(c++)