Skip to content

Commit 69fbb64

Browse files
Add files via upload
1 parent a5c371c commit 69fbb64

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// 第一种思路,完全新建一个链表,不去破坏原始的两个小链表
2+
// 12ms 43.69%
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode(int x) : val(x), next(NULL) {}
10+
* };
11+
*/
12+
class Solution
13+
{
14+
public:
15+
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
16+
{
17+
ListNode *head = new ListNode(0), *rear = head;
18+
19+
// 循环判断直到两个链表有一个为空
20+
while (l1 && l2)
21+
{
22+
int minValue;
23+
24+
if (l1->val <= l2->val)
25+
{
26+
minValue = l1->val;
27+
l1 = l1->next;
28+
}
29+
else
30+
{
31+
minValue = l2->val;
32+
l2 = l2->next;
33+
}
34+
35+
rear->next = new ListNode(minValue);
36+
rear = rear->next;
37+
}
38+
39+
// 将剩下的链表接到总链表的后边
40+
for (ListNode *rest = l1 ? l1 : l2;rest;rest = rest->next)
41+
{
42+
rear->next = new ListNode(rest->val);
43+
rear = rear->next;
44+
}
45+
46+
return head->next;
47+
}
48+
};
49+
50+
// 第二种思路,破坏原始的两个小链表,将一个链表插入到另外一个链表中
51+
// 12ms 43.69%
52+
53+
/**
54+
* Definition for singly-linked list.
55+
* struct ListNode {
56+
* int val;
57+
* ListNode *next;
58+
* ListNode(int x) : val(x), next(NULL) {}
59+
* };
60+
*/
61+
class Solution {
62+
public:
63+
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
64+
65+
if (!l1) return l2;
66+
if (!l2) return l1;
67+
68+
ListNode *head;
69+
if (l1->val > l2->val)
70+
{
71+
ListNode *temp = l1;
72+
l1 = l2;
73+
l2 = temp;
74+
}
75+
head = l1;
76+
77+
// 循环插入直到两个链表有一个为空
78+
while(l1 && l2)
79+
{
80+
while (l1->next && l1->next->val <= l2->val)
81+
l1 = l1->next;
82+
83+
if (!l1->next)break;
84+
85+
ListNode *temp = l2;
86+
l2 = l2->next;
87+
88+
temp->next = l1->next;
89+
l1->next = temp;
90+
91+
l1 = l1->next;
92+
}
93+
94+
// 将剩下的链表接到总链表的后边
95+
if (!l1->next)
96+
l1->next = l2;
97+
return head;
98+
}
99+
};

0 commit comments

Comments
 (0)