-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathMergeTwoSortedList
130 lines (85 loc) · 4.04 KB
/
MergeTwoSortedList
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package Amazon;
import java.util.List;
import java.util.LinkedList;
public class MergeTwoSortedList {
public List<Integer> merge(List<Integer> list1, List<Integer> list2) {
if((list1 == null) & (list2 == null)) {
return null;
}
if(list1 == null) {
return list2;
}
if(list2 == null) {
return list1;
}
int pointerList1 = 0;
int pointerList2 = 0;
int totalsize = list1.size() + list2.size();
List<Integer> list = new LinkedList<Integer>();
for(int i = 0; i < totalsize; i++) {
if ((pointerList1 < list1.size()) && (pointerList2 < list2.size()) ) {
if (list1.get(pointerList1) <= list2.get(pointerList2)) {
list.add(list1.get(pointerList1));
pointerList1++;
} else {
list.add(list2.get(pointerList2));
pointerList2++;
}
} else {
if (pointerList1 < list1.size()) {
while (true) {
if (pointerList1 >= list1.size()) {
break;
}
list.add(list1.get(pointerList1));
pointerList1++;
}
break;
} else {
while (true) {
if (pointerList2 >= list2.size()) {
break;
}
list.add(list2.get(pointerList2));
pointerList2++;
}
break;
}
}
}
return list;
}
public static void main(String[] args) {
MergeTwoSortedList m = new MergeTwoSortedList();
List<Integer> list1 = new LinkedList<Integer>();
list1.add(1);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(7);
List<Integer> list2 = new LinkedList<Integer>();
list2.add(2);
list2.add(4);
list2.add(5);
list2.add(6);
list2.add(8);
list2.add(9);
list2.add(10);
System.out.println(m.merge(list1, list2));
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}