# Code language: Python classSolution: definsert(self, head: 'Node', insertVal: int) -> 'Node': if head isNone: head = Node(insertVal) head.next = head return head # 找 p.val <= insertVal <= p.next.val p = head whilenot (p.val <= insertVal <= p.next.val): p = p.next # 有两种情况找不到这样的位置 # 一是给定值比所有结点值都大, 二是给定值比所有结点值都小 # 这两种情况的插入位置都在链表唯一非递增的位置 if p == head or (p.val > p.next.val and (insertVal >= p.val or insertVal <= p.next.val)): break p.next = Node(insertVal, p.next) return head
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Code language: Java classSolution { public Node insert(Node head, int insertVal) { if (head == null) { Nodeans=newNode(insertVal); ans.next = ans; return ans; } Nodep= head; while (!(p.val <= insertVal && insertVal <= p.next.val)) { p = p.next; if (p == head || (p.val > p.next.val && (insertVal >= p.val || insertVal <= p.next.val))) break; } p.next = newNode(insertVal, p.next); return head; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Code language: C++ classSolution { public: Node* insert(Node* head, int insertVal){ if (head == nullptr) { Node* ans = newNode(insertVal); ans->next = ans; return ans; } Node* p = head; while (!(p->val <= insertVal && insertVal <= p->next->val)) { p = p->next; if (p == head || (p->val > p->next->val && (insertVal >= p->val || insertVal <= p->next->val))) break; } p->next = newNode(insertVal, p->next); return head; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Code language: C# publicclassSolution { public Node Insert(Node head, int insertVal) { if (head == null) { Node ans = new Node(insertVal); ans.next = ans; return ans; } Node p = head; while (!(p.val <= insertVal && insertVal <= p.next.val)) { p = p.next; if (p == head || (p.val > p.next.val && (insertVal >= p.val || insertVal <= p.next.val))) break; } p.next = new Node(insertVal, p.next); return head; } }