Merge Sorted Lists (Java merge ordered list space complexity O (1))

Source: Internet
Author: User

Topic:

Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.

Analysis: merge Two ordered sequences, a key step in this merge sort. This is to merge two ordered single-linked lists. Due to the particularity of the linked list, only the spatial complexity of constants is needed in the merging.

Coding:

 PublicListNode mergetwolists (listnode L1, ListNode L2) {if(L1 = =NULL&& L2 = =NULL)            return NULL; if(L1 = =NULL&& L2! =NULL)            returnL2; if(L2 = =NULL&& L1! =NULL)            returnL1; ListNode P=L1; ListNode Q=L2; ListNode Newhead=NewListNode (-1);//Defining head NodesListNode r =Newhead;  while(P! =NULL&& Q! =NULL){            if(P.val <q.val) {R.next=p;//here, the node to be sorted is stitched directly to the new node, instead of creating a new node.                Space-saving complexity. P=P.next; R=R.next; } Else{R.next=Q; Q=Q.next; R=R.next; }        }                if(P! =NULL) R.next=p; if(Q! =NULL) R.next=Q; returnNewhead.next; }

Merge Sorted Lists (Java merge ordered list space complexity O (1))

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.