-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample21.java
91 lines (66 loc) · 2.13 KB
/
Example21.java
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
package applications.algorithms;
import datastructs.adt.SingleLinkedList;
/** Category: Algorithms
* ID: Example21
* Description: Merge two sorted linked lists
* Taken From:
* Details:
* TODO
*/
public class Example21 {
public static SingleLinkedList<Integer> mergeLinkedLists(SingleLinkedList<Integer> list1, SingleLinkedList<Integer> list2){
if(list1 == null && list2 == null){
return new SingleLinkedList<>();
}
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
SingleLinkedList<Integer> result = new SingleLinkedList<>();
SingleLinkedList<Integer>.Node head1 = list1.front();
SingleLinkedList<Integer>.Node head2 = list2.front();
while( head1 != null && head2 != null){
Integer val1 = head1.getData();
Integer val2 = head2.getData();
System.out.println(" value1: "+val1+" value2: "+val2);
if( val1 < val2){
result.pushBack(val1);
head1 = head1.getNext();
}
else{
result.pushBack(val2);
head2 = head2.getNext();
}
}
// pick up what is left
while ( head1 != null ){
result.pushBack(head1.getData());
head1 = head1.getNext();
}
while ( head2 != null ){
result.pushBack(head2.getData());
head2 = head2.getNext();
}
return result;
}
public static void main(String[] args){
SingleLinkedList<Integer> list1 = new SingleLinkedList<>();
list1.pushBack(1);
list1.pushBack(2);
list1.pushBack(3);
list1.pushBack(6);
list1.pushBack(7);
SingleLinkedList<Integer> list2 = new SingleLinkedList<>();
list2.pushBack(1);
list2.pushBack(4);
list2.pushBack(5);
list2.pushBack(6);
list2.pushBack(7);
list2.pushBack(8);
list2.pushBack(9);
SingleLinkedList<Integer> result = Example21.mergeLinkedLists(list1, list2);
result.print();
}
}