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