2016-06-08

Merging two Sorted Linked List using java

Merge two linked list that are aleady sorted and return a new sorted list.

Implement this method :

  1. Node MergeLists(Node list1, Node list2){
  2. // your code here
  3. }


Solution:




  1. class Node{
  2.     int data;
  3.     Node next;
  4. Node MergeLists(Node list1, Node list2) {
  5.   if (list1 == null) return list2;
  6.   if (list2 == null) return list1;

  7.   if (list1.data < list2.data) {
  8.     list1.next = MergeLists(list1.next, list2);
  9.     return list1;
  10.   } else {
  11.     list2.next = MergeLists(list2.next, list1);
  12.     return list2;
  13.   }
  14. }
  15. }

No comments:

Post a Comment