trick 1: If the iteration is for two linked lists with different length. You can use while (l1 || l2), inside the while loop, you can maintain the loop invariance by checking the nullptr and considering all edge cases.
It is easy to handle the common case prev <= insertVal <= curr.
For the special case when "wrap around" the circle, it could be insertVal is the max or min, but in both cases, the insertion operation is the same.
"""# Definition for a Node.class Node: def __init__(self, val=None, next=None): self.val = val self.next = next"""classSolution:definsert(self,head:'Node',insertVal:int)->'Node':node=Node(insertVal)node.next=nodeifnothead:returnnodeprev,curr=head,head.nextwhilenotprev.val<=insertVal<=curr.valandnotprev.val>curr.val>insertValandnotinsertVal>prev.val>curr.val:prev,curr=prev.next,curr.nextifprev==head:breakprev.next=nodenode.next=currreturnhead
/*// Definition for a Node.class Node {public: int val = NULL; Node* next = NULL; Node() {} Node(int _val, Node* _next) { val = _val; next = _next; }};*/classSolution{public:Node*insert(Node*head,intinsertVal){if(head==nullptr){head=newNode(insertVal,nullptr);head->next=head;returnhead;}Node*prev=head;Node*next=head->next;while(!(prev->val<=insertVal&&insertVal<=next->val)&&!(prev->val>next->val&&insertVal<next->val)&&!(prev->val>next->val&&insertVal>prev->val)){prev=prev->next;next=next->next;if(prev==head)break;}prev->next=newNode(insertVal,next);returnhead;}};