[Leetcode] merge two sorted lists

Source: Internet
Author: User

Merge two sorted lists

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

Algorithm ideas:

Based on L1, L2 points are inserted into L1 one by one. The two linked lists are traversed once. I have not optimized the time complexity O (m + n ), space complexity O (1)

 

1 public class solution {2 Public listnode mergetwolists (listnode L1, listnode l2) {3 if (L1 = NULL) return L2; 4 If (L2 = NULL) return L1; 5 listnode head = new listnode (1); 6 head. next = L1; 7 listnode pre = head; 8 listnode node = L2; 9 While (L2! = NULL) {10 node = L2; 11 while (PRE. Next! = NULL & pre. next. val <= node. val) {12 pre = pre. next; 13} 14 L2 = node. next; 15 node. next = pre. next; 16 pre. next = node; 17 pre = node; // if this sentence is deleted, L2 scans both sides, L1 scans again, but the time complexity remains unchanged 18} 19 Return head. next; 20} 21}

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.