/*// Definition for a Node.class Node { public int val; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _next) { val = _val; next = _next; }};*/classSolution{publicNodeinsert(Nodehead,intinsertVal){Nodenode=newNode(insertVal);if(head==null){node.next=node;returnnode;}Nodeprev=head,curr=head.next;while(curr!=head){if((prev.val<=insertVal&&insertVal<=curr.val)||(prev.val>curr.val&&(insertVal>=prev.val||insertVal<=curr.val))){break;}prev=curr;curr=curr.next;}prev.next=node;node.next=curr;returnhead;}}
/*// Definition for a Node.class Node {public: int val; Node* next; Node() {} Node(int _val) { val = _val; next = NULL; } Node(int _val, Node* _next) { val = _val; next = _next; }};*/classSolution{public:Node*insert(Node*head,intinsertVal){Node*node=newNode(insertVal);if(!head){node->next=node;returnnode;}Node*prev=head,*curr=head->next;while(curr!=head){if((prev->val<=insertVal&&insertVal<=curr->val)||(prev->val>curr->val&&(insertVal>=prev->val||insertVal<=curr->val)))break;prev=curr;curr=curr->next;}prev->next=node;node->next=curr;returnhead;}};
1 2 3 4 5 6 7 8 910111213141516171819202122232425
/** * Definition for a Node. * type Node struct { * Val int * Next *Node * } */funcinsert(head*Node,xint)*Node{node:=&Node{Val:x}ifhead==nil{node.Next=nodereturnnode}prev,curr:=head,head.Nextforcurr!=head{if(prev.Val<=x&&x<=curr.Val)||(prev.Val>curr.Val&&(x>=prev.Val||x<=curr.Val)){break}prev,curr=curr,curr.Next}prev.Next=nodenode.Next=currreturnhead}