File tree Expand file tree Collapse file tree 1 file changed +6
-18
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +6
-18
lines changed Original file line number Diff line number Diff line change @@ -58,9 +58,10 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> divideInTwoHalves(Si
58
58
return slow ;
59
59
}
60
60
61
+
61
62
/**
62
63
* Merges two sorted lists starting at {@param node1} and {@param node2}
63
- * into one and returns its {@code head} reference .
64
+ * into one and returns its starting node .
64
65
* <p/>
65
66
* This method is similar to {@link me.ramswaroop.linkedlists.MergeTwoSortedLists#mergeTwoSortedLists}
66
67
*
@@ -75,21 +76,8 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> mergeTwoSortedLists(
75
76
76
77
if (node1 == null && node2 == null ) return null ;
77
78
78
- if (node1 == null ) {
79
- head = node2 ;
80
- curr2 = curr2 .next ;
81
- } else if (node2 == null ) {
82
- head = node1 ;
83
- curr1 = curr1 .next ;
84
- } else if (node1 .item .compareTo (node2 .item ) < 0 ) {
85
- head = node1 ;
86
- curr1 = curr1 .next ;
87
- } else {
88
- head = node2 ;
89
- curr2 = curr2 .next ;
90
- }
79
+ head = curr = new SingleLinkedNode <>(null ); // dummy node
91
80
92
- curr = head ;
93
81
while (curr1 != null || curr2 != null ) {
94
82
// handle cases where either of the list run out first
95
83
if (curr1 == null ) {
@@ -116,15 +104,15 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> mergeTwoSortedLists(
116
104
curr = curr .next ;
117
105
}
118
106
119
- return head ;
107
+ return head . next ;
120
108
}
121
109
122
110
public static void main (String a []) {
123
111
SingleLinkedList <Integer > linkedList = new SingleLinkedList <>();
124
- linkedList .add (33 );
125
112
linkedList .add (21 );
113
+ linkedList .add (33 );
126
114
linkedList .add (89 );
127
- linkedList .add (55 );
115
+ linkedList .add (21 );
128
116
linkedList .add (44 );
129
117
linkedList .add (67 );
130
118
linkedList .printList ();
You can’t perform that action at this time.
0 commit comments