-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathMergeTwoSortedLists.java
More file actions
79 lines (73 loc) · 1.86 KB
/
MergeTwoSortedLists.java
File metadata and controls
79 lines (73 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Author: Shobhit Behl (LC: shobhitbruh)
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy=new ListNode(-1);
ListNode x=dummy;
ListNode p1=list1;
ListNode p2=list2;
while(p1!=null&&p2!=null){
if(p1.val<p2.val){
x.next=p1;
p1=p1.next;
}else{
x.next=p2;
p2=p2.next;
}
x=x.next;
}
while(p1!=null){
x.next=p1;
p1=p1.next;
x=x.next;
}
while(p2!=null){
x.next=p2;
p2=p2.next;
x=x.next;
}
return dummy.next;
}
}
// @saorav21994
// TC : O(n)
// SC : O(n)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode res = new ListNode(-1);
ListNode head = res;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
res.next = new ListNode(l1.val);
res = res.next;
l1 = l1.next;
}
else {
res.next = new ListNode(l2.val);
res = res.next;
l2 = l2.next;
}
}
while (l1 != null) {
res.next = new ListNode(l1.val);
res = res.next;
l1 = l1.next;
}
while (l2 != null) {
res.next = new ListNode(l2.val);
res = res.next;
l2 = l2.next;
}
res.next = null;
return head.next;
}
}