-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeTwoSortedList.java
More file actions
89 lines (68 loc) · 1.65 KB
/
Copy pathmergeTwoSortedList.java
File metadata and controls
89 lines (68 loc) · 1.65 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
80
81
82
83
84
85
86
87
88
89
package LeetCode;
class ListNode3 {
int val;
ListNode3 next;
ListNode3(int x) {
val = x;
next = null;
}
}
public class mergeTwoSortedList {
public static ListNode3 mergeTwoLists(ListNode3 list1, ListNode3 list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode3 start = null , temp = start ;
if(list1.val <= list2.val){
start = new ListNode3(list1.val);
list1 = list1.next;
temp = start;
}
else{
start = new ListNode3(list2.val);
list2 = list2.next;
temp = start;
}
while(list1!= null && list2 != null){
if(list1.val <= list2.val){
start.next = new ListNode3(list1.val);
start = start.next;
list1 = list1.next;
}
else{
start.next = new ListNode3(list2.val);
start = start.next;
list2 = list2.next;
}
}
if(list1 == null){
while(list2 != null){
start.next = new ListNode3(list2.val);
start = start.next;
list2 = list2.next;
}
}
if(list2 == null){
while(list1 != null){
start.next = new ListNode3(list1.val);
start = start.next;
list1 = list1.next;
}
}
return temp;
}
public static void main(String[] args) {
ListNode3 firstList = new ListNode3(1);
firstList.next = new ListNode3(5);
firstList.next.next = new ListNode3(9);
ListNode3 secList = new ListNode3(3);
secList.next = new ListNode3(6);
secList.next.next = new ListNode3(8);
ListNode3 res = mergeTwoLists(firstList,secList);
while(res != null){
System.out.println(res.val);
res = res.next;
}
}
}