C/C++: 将两个单链表合并为一个单链表并排序

#include 
using namespace std;

typedef struct lst
{
	int data;
	struct lst* next;
}LNode;

LNode* Init()//创建单链表
{
	int x = 0;
	LNode* head, * p, * q;
	head = new LNode;
	q = head;
	cout << "建立单链表" << endl;
	cin >> x;
	while (x != -1) {
		p = new LNode;
		q->next = p;
		p->data = x;
		q = p;
		cin >> x;
	}
	q->next = NULL;
	return head;
}
void Merge(LNode* L0, LNode* L1, LNode* L2)
{
	LNode* pa = NULL, * pb = NULL, * pc = NULL, * p = NULL;
	p = L2;
	pa = L0->next;
	pb = L1->next;
	pc = L2 = L0;
	while (pa && pb)
	{
		if (pa->data <= pb->data)
		{
			pc->next = pa;
			pc = pc->next;
			pa = pa->next;
		}
		else
		{
			pc->next = pb;
			pc = pc->next;
			pb = pb->next;
		}
	}
	pc->next = pa ? pa : pb;//长度不同时,判断谁为真就继续往下接谁
	//以下为检验部分
	p = L2->next;
	while (p)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}
void Sort(LNode* head)//排序
{
	LNode* p = NULL, * q = NULL, * r = NULL, * t = NULL;
	int flag = 1;
	while (flag) {
		p = head;
		q = head->next;
		flag = 0;
		while (q != NULL) {
			r = q->next;
			if (r == NULL) {
				break;
			}
			else if (q->data > r->data) {
				t = r->next;
				q->next = t;
				r->next = q;
				p->next = r;
				p = r;
				q = p->next;
				r = q->next;
				flag = 1;
			}
			else {
				p = q;
				q = p->next;
			}
		}
	}
}
int main(void)
{
	LNode* head = NULL, * nhead = NULL;
	
	head = Init();
	Sort(head);

	cout << endl << "再次输入一个链表:" << endl;
	nhead = Init();
	Sort(nhead);

	LNode* mhead = NULL;
	Merge(head, nhead, mhead);
	return 0;
}

你可能感兴趣的:(c语言,c++,算法)