File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments