Combining two sequential single-linked lists with algorithm summary

Source: Internet
Author: User

Given the head node Head1 and head2 of the two ordered single-linked lists, merge the two ordered linked lists, the merged list is still orderly, and return the head node of the merged list

Suppose that two lists of the length of M and N directly give a time complexity of (m+n) additional space complexity O (1)

1 if one of the two linked lists is empty, you do not need to merge to return another linked header node

2 comparing the values of Head1 and head2, the smaller is the head node of the merged list, which is the head node in the next step, and all the nodes of the other list are inserted into the list at once.

3 It is advisable to set the head node in the linked list 1, another linked list 2, 1 and 2 are traversed from the head, compare the value of two nodes per traversal, recorded as Cur1 and CUR2 and then make different adjustments based on the size of the same time with a variable pre to represent the node with the last comparison value is small

If the two linked list has an end, go to the next step

If the list 1 is finished first, at this time cur1=null, the pre is the last node of the list 1, then the next pointer of the pre is pointed to the current node cur2 of List 2.

Returns the head node of the merged list

Code:

Package Tt;public class Test114 {public class Node{public int value;public node next;public node (int data) {This.value=data ;}} Public node Merge (node Head1, node head2) {if (Head1==null | | head2==null) {  return head1! = null? Head1:head2;} Node head = Head1.value < Head2.value? Head1:head2; Node Cur1 = head==head1? Head1:head2; Node CUR2 = head==head1? Head2:head1; Node pre = NULL; Node Next =null;while (cur1! = NULL && CUR2! = null) {if (Cur1.value <= cur2.value) {pre=cur1;cur1=cur1.next;} else {next=cur2.next;pre.next=cur2;cur2.next=cur1;pre=cur2;cur2=next;}} Pre.next=cur1==null? Cur2:cur1;return head;}}

  

 

Combining two sequential single-linked lists with algorithm summary

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.