题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路:
1)定义一个头指针head,定义pNode为当前操作结点
2)判断链表1和链表2,将小的连接在pNode->next上,然后pNode = pNode->next
3)将剩下的非空链表链接上
4)返回head->next
1 #include <iostream>
2 #include <malloc.h>
3 using namespace std;
4 struct ListNode {
5 int val;
6 struct ListNode *next;
7 ListNode(int x) :
8 val(x), next(NULL) {
9 }
10 };
11 class Solution {
12 public:
13 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
14 {
15 ListNode *head = new ListNode(-1);//头指针
16 ListNode *pNode = head;//当前操作结点
17 while(pHead1 != NULL && pHead2 != NULL)
18 {
19 if(pHead1->val <= pHead2->val)//小的链接在链表上
20 {
21 pNode->next = pHead1;
22 pNode= pNode->next;
23 pHead1 = pHead1->next;
24 }
25 else
26 {
27 pNode->next = pHead2;
28 pNode = pNode->next;
29 pHead2 = pHead2->next;
30 }
31 }
32 //剩余的非空链表全部链接上
33 while(pHead1 != NULL)
34 {
35 pNode->next = pHead1;
36 pNode= pNode->next;
37 pHead1 = pHead1->next;
38 }
39 while(pHead2 != NULL)
40 {
41 pNode->next = pHead2;
42 pNode= pNode->next;
43 pHead2 = pHead2->next;
44 }
45 return head->next;
46 }
47 };
48 ListNode *CreateList(int n)
49 {
50 ListNode *head;
51 ListNode *p,*pre;
52 int i;
53 head=(ListNode *)malloc(sizeof(ListNode));
54 head->next=NULL;
55 pre=head;
56 for(i=1;i<=n;i++)
57 {
58 p=(ListNode *)malloc(sizeof(ListNode));
59 cin>>p->val;
60 pre->next=p;
61 pre=p;
62 }
63 p->next=NULL;
64
65 return head->next;
66 }
67 /*-------------------------输出链表-----------------------------------*/
68 void PrintList(ListNode *h)
69 {
70 ListNode *p;
71
72 p=h;//不带空的头结点
73 while(p)
74 {
75 cout<<p->val<<" ";
76 p=p->next;
77 cout<<endl;
78 }
79 }
80 int main()
81 {
82 int n1;
83 int n2;
84 ListNode *h1;
85 ListNode *h2;
86 ListNode *h;
87 cout<<"输入链表1的结点数目"<<endl;
88 cin>>n1;
89 h1 = CreateList(n1);
90 cout<<"链表1为:"<<endl;
91 PrintList(h1);
92 cout<<"输入链表2的结点数目"<<endl;
93 cin>>n2;
94 h2 = CreateList(n2);
95 cout<<"链表2为:"<<endl;
96 PrintList(h2);
97 Solution s;
98 h = s.Merge(h1,h2);
99 cout<<"合并后链表为: "<<endl;
100 PrintList(h);
101 return 0;
102 }

来源:https://www.cnblogs.com/qqky/p/6860053.html