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.
The title means merging two linked lists and not using extra space (the new chain is made up of two links)
Ideas:
Simple, direct definition of two pointers, pointing to two chains, and comparing the size of the pointing node if the pointer points to a small value, then let the new chain point to the small one, and the pointer moves backwards
, the current pointer of the new chain also moves backwards. Until one of the two chains is traversed to the end, then the remaining chains are stitched to the new chain
The code is as follows:
<span style= "FONT-SIZE:18PX;" >/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *mergetwolists (ListNode *l1, ListNode *l2) { if (l1==null) return L2; if (l2==null) return L1; ListNode *p,*q; P=L1; Q=L2; ListNode *result=new listnode (0); ListNode *temp =result; while (p&&q) { if (p->val<q->val) { temp->next=p; temp=p; p=p->next; } else { temp->next=q; temp=q; q=q->next; } } if (p) { temp->next=p; } if (q) { temp->next=q; } Return result->next; }}; </span>
Merge Sorted Lists leetcode