问题描述:
- 给定循环单调非递减链表中的一个点,向这个链表中插入一个新元素
insertVal
,使这个链表仍保持单调非递增。
核心思路:
- 由题目可知链表为循环单链,且顺着链表移动可以得知链表是单调非递增的,所以只需要遍历链表,在合适的位置插入节点即可。
- 插入的位置只有两种:在某两个数之间、在最大值和最小值之间。
- 因而在遍历的过程中,遇到合适的位置就可以直接插入,即
cur->val <= insertVal and cur->next->val >= insertVal
。 - 但是遇到最大值节点和最小值节点的连接时不能直接插入,因为题目给定的起始指针不一定是链表中最小元素的指针,这就意味着从给定指针起移动到最大节点未必走完全程。【所以需要做的是保存好最大值指针,如果走完一遍全程仍无合适插入位置,则说明需要插入到最大值指针后面】
- 如果链表为空,则创建一个自引的节点即可。
代码实现:
class Solution
{
public:
Node* insert(Node* head, int insertVal)
{
Node* new_node = new Node(insertVal);
if(!head)
{
new_node->next = new_node;
return new_node;
}
Node* max_node = head;
Node* cur = head;
while(1)
{
if(cur->val <= insertVal and cur->next->val >= insertVal)
{
new_node->next = cur->next;
cur->next = new_node;
return head;
}
if(cur->val >= max_node->val)
max_node = cur;
cur = cur->next;
if(cur == head) break;
}
new_node->next = max_node->next;
max_node->next = new_node;
return head;
}
};