Common algorithm problems: single-linked table two-way merge

Source: Internet
Author: User

Title: Existing two incremental single-linked list L1 and L2, design an algorithm to merge all nodes of L1 and L2 into the incremented single-linked list L3. Requirements: Space complexity is O (1).

Ideas: The topic can be used in two ways to merge ideas, but the title requires space complexity of O (1), so can not replicate nodes, can only destroy L1 and L2 to insert nodes into the L3.

Code:

voidMerge (linklist&L1,linklist&L2,linklist&L3) {linklist*P=L1.Head -Next*Q=L2.Head -Next Linklist*P1,*Q1,*R L1.Head -Next=NULL;//Set L1, L2 to empty tableL2.Head -Next=NULL; R=L3.Head while(p!=NULL&&Q!=NULL)///Two tables are not traversed at the end of the{if(p -Data<Q -Data) {P1=P -Next//Insert the nodes in the L1 into the L3R -Next=P;r=P P=P1; }Else{Q1=Q -Next//Insert the nodes in the L2 into the L3R -Next=Q;r=Q Q=Q1; }    } while(p!=NULL)//If L1 is not traversed, all remaining nodes are inserted into the L3{P1=P -Next R -Next=P;r=P P=P1; } while(q!=NULL)//If L2 is not traversed, all remaining nodes are inserted into the L3{Q1=Q -Next R -Next=Q;r=Q Q=Q1; } r -Next=NULL;//Set the L3 tail node to null}

There is no new node in the algorithm, so the spatial complexity is O (1).

Common algorithm problems: single-linked table two-way merge

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.