输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
合并链表,带测试链表。注意建立的链表头是空的。
#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);
}
链表合并算法
本文介绍了一种合并两个单调递增链表的算法,确保合成后的链表也保持单调不减的特性。通过创建链表、合并操作及打印链表内容的具体实现,展示了如何有效地将两个有序链表整合为一个新的有序链表。
5万+

被折叠的 条评论
为什么被折叠?



