The Java implementation merges two sorted list instance code

  • 2020-04-01 02:38:13
  • OfStack

One of the great things about Java, compared to C++, is that there are no confusing Pointers, but there is no denying that in certain situations, Pointers do count. Although Pointers are not explicitly defined in Java, because of the idea of classes, we can use classes to manipulate Pointers. Small two, top chestnut -- merge two sorted lists, output the header of the list after merging, and the elements in the list after merging are ordered.

Keep in mind that in Java, a node in a list is really an object instantiated by a class.

The sample code is as follows:


package DecemberOf2013;
class ListNode{
    int val;
    ListNode next;
    public ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}
public class MergeTowSortedLists {

    public ListNode mergeLists(ListNode l1, ListNode l2){

        ListNode p1 = l1;
        ListNode p2 = l2;

        ListNode fadeHead = new ListNode(0);
        ListNode pHead = fadeHead;

        while(p1 != null && p2 != null){
            if(p1.val <= p2.val){
                pHead.next = p1;
                p1 = p1.next; 
            }
            else{
                pHead.next = p2;
                p2 = p2.next; 
            }
            pHead = pHead.next;
        }

        if(p1 != null){
            pHead.next = p1;
        }
        else{
            pHead.next = p2;
        }

        return fadeHead.next;
    }
}


Related articles: