There are many if-else
conditions in my code
Question 1:
I am looking for suggestions to minimize if else conditions. Also, Code in Step 1 and Step2 is almost same. Is there any way to make it neat and improve readability
Question 2:
I am looking for suggestions to improve main method and which methods can be called with an instance or class variables. That technique I will apply to all my LinkedList related questions
public class MergeTwoSortedLists {
public Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public void push(int data) {
Node n = new Node(data);
if ( head == null ) {
head = n;
} else {
Node temp = head;
while (temp.next != null ) {
temp = temp.next;
}
temp.next = n;
}
}
public static void printList(Node head) {
Node temp = head;
while ( temp != null ) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
MergeTwoSortedLists l1 = new MergeTwoSortedLists();
l1.push(1);
l1.push(2);
l1.push(13);
l1.push(14);
l1.push(50);
printList(l1.head);
MergeTwoSortedLists l2 = new MergeTwoSortedLists();
l2.push(10);
l2.push(20);
l2.push(55);
printList(l2.head);
Node res = sortTwoLists(l1.head, l2.head);
printList(res);
}
public static Node sortTwoLists(Node headA, Node headB) {
Node s = null;
Node res = null;
if ( headA == null ) return headB;
if ( headB == null ) return headA;
/* Step 1: Set the s with less value */
if ( headA!= null && headB!= null ) {
if ( headA.data < headB.data ) {
s = headA;
headA = s.next;
} else {
s = headB;
headB = s.next;
}
}
res = s;
/* Step2: Iterate oer two lists and keep moving s accordingly */
while ( headA!= null && headB!= null ) {
if ( headA.data < headB.data ) {
s.next = headA;
s = headA;
headA = s.next;
} else {
s.next = headB;
s = headB;
headB = s.next;
}
}
if ( headA == null ) {
s.next = headB;
}
if ( headB == null ) {
s.next = headA;
}
return res;
}
}