C++合并两个有序单链表并保存在它们的节点中

#include<iostream>
#define ElemType int
using namespace std;

typedef struct Node {
	ElemType data;
	struct Node *next;
};

void Create(Node *&l) {  //尾插法
	int x;
	l->next = NULL; //头结点
	Node *s,*r = l;  //r为表尾指针
	cin >> x;
	while (x != -1) {
		s = new Node;
		s->data = x;
		r->next = s;
		r = s;
		cin >> x;
	}
	r->next = NULL;
}

void Print(Node *&l) { //输出链表中的数据
	Node *p = l->next;
	while (p != NULL) {
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

void Delete(Node *&l) { //单链表的删除操作
	Node *p = l;
	Node *q = l->next;  //保存后继指针,防止断链

	while (p!= NULL ) {
		delete p;
		p = q;
		if (q != NULL) {
			q = q->next;
		}
	}
}

void Merge(Node *&A, Node *&B) {
	Node *a = A->next, *b = B->next, *r = NULL;
	A->next = NULL; //先保存一个只有头结点的单链表
	while (a&&b) {
		if (a->data > b->data) {
			r = b->next;  //保存后继指针
			b->next = A->next;
			A->next = b;
			b = r;  //下一次循环
		}
		else {
			if (a->data < b->data) {
				r = a->next;
				a->next = A->next;
				A->next = a;
				a = r;
			}
			else {
				//因为存在两个数相等,需要插入两次
				r = b->next;  //保存后继指针
				b->next = A->next;
				A->next = b;
				b = r;  //下一次循环

				r = a->next;
				a->next = A->next;
				A->next = a;
				a = r;
			}
		}
	}

	if (a) {
		b = a;  //判断是哪一个链表先结束
	}

	while (b) {
		r = b->next;
		b->next = A->next;
		A->next = b;
		b = r;
	}

	//delete B;

}
int main() {
	Node *A = new Node; //新建结点,并且创建指针
	Node *B = new Node; //新建结点,并且创建指针
	Create(A);
	Create(B);
	Print(A);
	Print(B);
	Merge(A, B);
	Print(A);
	Delete(A);  //释放内存
	system("pause");
	return 0;
}

/*
1 2 3 4 5 6 7 8 9 -1
4 5 6 7 8 9 10 11 12 -1

*/

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/80142354