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.
Analysis: merge Two ordered sequences, a key step in this merge sort. This is to merge two ordered single-linked lists. Due to the particularity of the linked list, only the spatial complexity of constants is needed in the merging.
Coding:
PublicListNode mergetwolists (listnode L1, ListNode L2) {if(L1 = =NULL&& L2 = =NULL) return NULL; if(L1 = =NULL&& L2! =NULL) returnL2; if(L2 = =NULL&& L1! =NULL) returnL1; ListNode P=L1; ListNode Q=L2; ListNode Newhead=NewListNode (-1);//Defining head NodesListNode r =Newhead; while(P! =NULL&& Q! =NULL){ if(P.val <q.val) {R.next=p;//here, the node to be sorted is stitched directly to the new node, instead of creating a new node. Space-saving complexity. P=P.next; R=R.next; } Else{R.next=Q; Q=Q.next; R=R.next; } } if(P! =NULL) R.next=p; if(Q! =NULL) R.next=Q; returnNewhead.next; }
Merge Sorted Lists (Java merge ordered list space complexity O (1))