@@ -154,7 +154,7 @@ private ListNode insertInSortedList(int value) {
154
154
return head ;
155
155
}
156
156
157
- private void getNthNodeFromEnd (int n ) {
157
+ private void getNthNodeFromEnd1 (int n ) {
158
158
159
159
if (head == null ) {
160
160
@@ -189,6 +189,26 @@ private void getNthNodeFromEnd(int n) {
189
189
System .out .println (mainPtr .data );
190
190
}
191
191
192
+ private static int getNthNodeFromEnd2 (int positionFromTail ) {
193
+ int index = 0 ;
194
+
195
+ ListNode current = head ;
196
+ ListNode result = head ;
197
+
198
+ while (current != null )
199
+ {
200
+ current = current .next ;
201
+
202
+ if (index > positionFromTail )
203
+ {
204
+ result =result .next ;
205
+ }
206
+ index ++;
207
+ }
208
+
209
+ return result .data ;
210
+ }
211
+
192
212
private ListNode reverseList () {
193
213
194
214
ListNode current = head ;
@@ -251,6 +271,54 @@ private boolean detectLoop() {
251
271
return false ;
252
272
}
253
273
274
+
275
+ static boolean compareLists (ListNode head1 , ListNode head2 ) {
276
+
277
+ ListNode current1 = head1 ;
278
+ ListNode current2 = head2 ;
279
+
280
+ int length1 = 0 ;
281
+ int length2 = 0 ;
282
+
283
+ while (current1 != null && current2 != null ) {
284
+ if (current1 .data != current2 .data ) {
285
+ return false ;
286
+ }
287
+ length1 ++;
288
+ length2 ++;
289
+
290
+ current1 = current1 .next ;
291
+ current2 = current2 .next ;
292
+ }
293
+
294
+ return length1 == length2 ;
295
+
296
+ }
297
+
298
+ public static ListNode removeDuplicates (ListNode head ) {
299
+
300
+ // if list is empty or if list contains a single node
301
+ if (head == null || head .next == null ){
302
+ return head ;
303
+ }
304
+
305
+ // having a reference for head node and then manipulating it further
306
+ ListNode current = head ;
307
+
308
+ // if head's next is null, it's the end of list
309
+ while (head .next !=null ){
310
+ // checking head's data with it's next data
311
+ if (head .data != head .next .data ){
312
+ head = head .next ;
313
+ }else {
314
+ head .next = head .next .next ;
315
+ }
316
+ }
317
+
318
+ return current ;
319
+ }
320
+
321
+
254
322
public static void main (String [] args ) {
255
323
256
324
SinglyLinkedList sll = new SinglyLinkedList ();
0 commit comments