Skip to content

Commit d44d2c1

Browse files
committed
Create Merge Two Sorted Lists.cpp
1 parent cc75396 commit d44d2c1

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Merge Two Sorted Lists.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
12+
// Start typing your C/C++ solution below
13+
// DO NOT write int main() function
14+
ListNode *p1=l1,*p2=l2;
15+
ListNode *head=NULL,*ptr=NULL;
16+
while (p1&&p2)
17+
{
18+
if (p1->val<p2->val)
19+
{
20+
if (!head)
21+
{
22+
head=ptr=p1;
23+
}
24+
else
25+
{
26+
ptr->next=p1;
27+
ptr=p1;
28+
}
29+
p1=p1->next;
30+
}
31+
else
32+
{
33+
if (!head)
34+
{
35+
head=ptr=p2;
36+
}
37+
else
38+
{
39+
ptr->next=p2;
40+
ptr=p2;
41+
}
42+
p2=p2->next;
43+
}
44+
}
45+
while (p1)
46+
{
47+
if (!head)
48+
{
49+
head=ptr=p1;
50+
}
51+
else
52+
{
53+
ptr->next=p1;
54+
ptr=p1;
55+
}
56+
p1=p1->next;
57+
}
58+
while (p2)
59+
{
60+
if (!head)
61+
{
62+
head=ptr=p2;
63+
}
64+
else
65+
{
66+
ptr->next=p2;
67+
ptr=p2;
68+
}
69+
p2=p2->next;
70+
}
71+
return head;
72+
}
73+
};

0 commit comments

Comments
 (0)