599.Insert into a Cyclic Sorted List
1.Description(Easy)
Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list. Return the inserted new node.
Notice
3->5->1
is a cyclic list, so3
is next node of1
.
3->5->1
is same with5->1->3
Example
Given a list, and insert a value4
:
3->5->1
Return5->1->3->4
2.Code
Following are the 3 cases to consider
1) prev→val ≤ x ≤ current→val:
Insert between prev and current.
2) x is the maximum or minimum value in the list:
Insert before the head. (ie, the head has the smallest value and its prev→val > head→val.
3) Traverses back to the starting point:
Insert before the starting point.
Last updated