链表题目整理

版权声明:本文为博主原创文章,转载请注明出处并附带本文链接。 https://blog.csdn.net/IOT_Flower/article/details/78386386

链表逆序:

void Reverse(Node *head)
{
	if (head == NULL)
		return;
	Node *pre, *cur, *nex;
	pre = head;
	cur = head->next;
	while (cur)
	{
		nex = cur->next;
		cur->next = pre;
		pre = cur;
		cur = nex;
	}
	head->next = NULL;
	head = pre;
}

链表归并:

Node *Merge(Node *head1, Node *head2)
{
	if (head1 == NULL)
		return head2;
	if (head2 == NULL)
		return head1;
	Node *head, *p1, *p2;
	if (head1->data < p2->data)
	{
		head = head1;
		p1 = head1->next;
		p2 = head2;
	}
	else
	{
		head = head2;
		p1 = head1;
		p2 = head2->next;
	}
	Node *cur = head;
	while (p1 != NULL && p2 != NULL)
	{
		if (p1->data <= p2->data)
		{
			cur->next = p1;
			cur = p1;
			p1 = p1->next;		
		}
		else
		{
			cur->next = p2;
			cur = p2;
			p2 = p2->next;
		}
	}
	if (p1 == NULL)
		cur->next = p2;
	if (p2 == NULL)
		cur->next = p1;
	return head;
}


猜你喜欢

转载自blog.csdn.net/IOT_Flower/article/details/78386386