java - How is sortingPtr variable getting updated in the code below? -
need understand how sortingptr variable getting updated.
public class mergesortedlinkedlists { public static node mergelinkedlists(node head1, node head2, node mergedhead){ node sortingptr = null; if(head1 == null && head2 != null){ return head2; } if(head1 == null && head2 == null){ return mergedhead; } while(head1 != null && head2 != null){ system.out.println("head1.data - " + head1.data); system.out.println("head2.data - " + head2.data); system.out.println("sortingptr - " + sortingptr); /*while(sortingptr != null){ system.out.print("sortingptr.data - " + sortingptr.data + " "); sortingptr = sortingptr.next; }*/ system.out.println(); if(head1.data < head2.data){ system.out.println("head1 < head2"); if(mergedhead != null){ mergedhead.next = head1; mergedhead = head1; } else{ sortingptr = head1; mergedhead = head1; } head1 = head1.next; } else{ system.out.println("head2 < head1"); if(mergedhead != null){ mergedhead.next = head2; mergedhead = head2; } else{ sortingptr = head2; mergedhead = head2; } head2 = head2.next; } } if(head1 == null){ mergedhead.next = head2; } if(head2 == null){ mergedhead.next = head1; } return sortingptr; } public static void main(string[] args) { singlylinkedlist linkedlist1 = new singlylinkedlist(); linkedlist1.head = linkedlist1.new node(10); linkedlist1.head.next = linkedlist1.new node(50); linkedlist1.head.next.next = linkedlist1.new node(70); linkedlist1.head.next.next.next = linkedlist1.new node(90); linkedlist1.head.next.next.next.next = linkedlist1.new node(100); singlylinkedlist linkedlist2 = new singlylinkedlist(); linkedlist2.head = linkedlist2.new node(20); linkedlist2.head.next = linkedlist2.new node(30); linkedlist2.head.next.next = linkedlist2.new node(40); linkedlist2.head.next.next.next = linkedlist2.new node(60); linkedlist2.head.next.next.next.next = linkedlist2.new node(80); singlylinkedlist mergedlist = new singlylinkedlist(); mergedlist.head = null; mergedlist.head = mergelinkedlists(linkedlist1.head, linkedlist2.head, mergedlist.head); node head = mergedlist.head; while(head != null){ system.out.print(head.data + " "); head = head.next; } } } class singlylinkedlist{ node head; class node{ int data; node next; node(int data){ this.data = data; next = null; } } }
i trying merge 2 sorted linked lists. method mergelinkedlists returning head of merged list in sortingptr variable. want understand how sortingptr variable getting updated return head of merged list in code mentioned above.
else{ sortingptr = head1; mergedhead = head1; }
and
else{ sortingptr = head2; mergedhead = head2; }
these block of codes ensure when mergedhead null(i.e. merging process has not started) set value of sortingptr value of mergedhead
Comments
Post a Comment