Leetcode Merge two Sorted Lists connect the two linked lists in order

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.

Translation:

Connect 2 ordered linked lists and return a new linked list

Ideas:

It is simple to iterate over each node, and the small words are added behind the new list. If one is empty, the other is connected to the end of the new list.

The second idea is to use a list as the benchmark, and then compare with the other, if the L2 node value is less than this, then the L2 node is inserted, and then L2 backward move one bit.

Code Listing 1:

  Public  static ListNode mergetwolists (ListNode L1, ListNode L2) {      ListNode root = new ListNode (0);      ListNode pre = root;      Pre.next = L1;      while (L1!=null && l2!=null)      {      if (L1.val > L2.val)//@1      {      ListNode next = l2.next;      L2.next = Pre.next;      Pre.next = L2;      L2 = Next;      Pre = Pre.next;      }      else       {      L1 = l1.next;      Pre = Pre.next;      }      }      if (L1 = = null)      {      pre.next = L2;      }  return root.next;    }
@1 first saves the next node of the L2, then inserts the L2 node into the L1, and finally points the L2 to the node you just saved.


Code Listing 2:

  Public  static ListNode mergetwolists (ListNode L1, ListNode L2) {      ListNode root = new ListNode (0);      ListNode pre = root;      Pre.next = L1;      while (true)      {      if (L1 = = null)      {      pre.next = L2;      break;      }      if (L2 = = null)      {      pre.next = L1;      break;      }      if (L1.val  < L2.val)      {      pre.next = L1;      L1 = L1.next;      }      else       {      Pre.next  = L2;      L2 = L2.next;      }      Pre = Pre.next;                 }  return root.next;    }
Code 2 is easier to understand. It's not a lot to explain.


Leetcode Merge two Sorted Lists connect the two linked lists in order

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.