合并链表,带测试链表。注意建立的链表头是空的。

链表合并算法
本文介绍了一种合并两个单调递增链表的算法,确保合成后的链表也保持单调不减的特性。通过创建链表、合并操作及打印链表内容的具体实现,展示了如何有效地将两个有序链表整合为一个新的有序链表。

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
合并链表,带测试链表。注意建立的链表头是空的。

#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
#include<stack>
using namespace std;
typedef struct ListNode
{
	int val;
	struct ListNode *next;
	ListNode(int x) :
		val(x), next(NULL) {
	}
}ListNode, *LinkList;

void CreateList(LinkList &L, int n)
{ // 给链表插入n个数据
	int i;
	LinkList p = NULL, q;
	L = (LinkList)malloc(sizeof(ListNode)); // 生成头结点
	L->next = NULL;
	q = L;
	//cout << "请输入" << n << "个数据:";
	for (i = 1; i <= n; i++)
	{
		p = (LinkList)malloc(sizeof(ListNode));
		p->val=i;
		//cin >> p->val;
		q->next = p;
		q = q->next;
	}
	p->next = NULL;
}



void Print(LinkList L)
{ // 输出链表结点内容
	ListNode *p;
	p = L->next;
	cout << endl << "L";
	while (p) {
		cout << "->" << p->val;
		p = p->next;
	}
	cout << endl;
}



class Solution {
public:
	ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
	{
		struct ListNode *temp3 = pHead1;

		struct ListNode *temp1 = (LinkList)malloc(sizeof(ListNode));;
		temp1->next = NULL;
			if (pHead1->val <= pHead2->val) {
				temp1 = pHead1;
				pHead1 = pHead1->next;
			}
			else {
				temp1 = pHead2;
				pHead2 = pHead2->next;
			}

		
		
		struct ListNode *temp2=temp1;
		

		
		
		
		while (pHead1 && pHead2)
		{
			
			if (pHead1->val <= pHead2->val)
			{
				
				temp2->next = pHead1;
				pHead1 = pHead1->next;
				temp2 = temp2->next;
			}
			else 
			{
				temp2->next = pHead2;
				pHead2 = pHead2->next;
				temp2 = temp2->next;
				
			}
			
			
		}
	
		
		if (pHead1 != NULL)
		{
			temp2->next = pHead1;
		}
		if (pHead2 != NULL)
		{
			temp2->next = pHead2;
		}
		return temp1;
		
	}
	
};

int main()
{
	//Solution a;
	vector<int> in = { 4, 7, 2, 1, 5, 3, 8, 6 }, b;
	int *a1 = new int;
	int *b1 = new int;
	int *c1 = new int;
	*a1 = 50;//源
	*b1 = 80;
	*c1 = 70;//
	b1  = a1;//b1地址被a1替换
	c1  = b1;//c1地址被a1替换   值为a1
	//地址改变。值改变
	//想要复制a1的内容 但是不改变a1的值
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
	////////////链表测试区
	LinkList L,L1,L3;
	CreateList(L, 6);
	CreateList(L1, 4);
	//Print(L);

	Solution a2;
	L3=a2.Merge(L,L1);
	Print(L3);




		//为什么head 指向p的头
      


	
	//cout << *c1;
	//cout << a.reOrderArray(in);
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值