| 每日一题做题记录,参考官方和三叶的题解 |
题目要求
思路:模拟
- 在有序的链表中找到合适的插入位置然后插入即可;
- 先构造一个指向自己的插入值节点;
- 当链表为空时返回自己;
- 当链表中只有一个节点直接插入;
- 遍历所有节点,找一个合适的位置,也就是当前节点的值小于,但是下一节点值大于;
- 注意在循环链表最大值和最小值的交界处的特殊判断,大于最大值或小于最小值就在这个交界插入。
Java
class Solution {
public Node insert(Node head, int insertVal) {
Node insertNode = new Node(insertVal);
insertNode.next = insertNode;
if (head == null)
return insertNode;
if (head.next == head) {
head.next = insertNode;
insertNode.next = head;
return head;
}
Node cur = head;
while (cur.next != head) {
if (insertVal >= cur.val && insertVal <= cur.next.val)
break;
if (cur.val > cur.next.val) {
if (insertVal > cur.val || insertVal < cur.next.val)
break;
}
cur = cur.next;
}
insertNode.next = cur.next;
cur.next = insertNode;
return head;
}
}
- 时间复杂度:
- 空间复杂度:
C++
class Solution {
public:
Node* insert(Node* head, int insertVal) {
Node *insertNode = new Node(insertVal);
insertNode->next = insertNode;
if (head == nullptr)
return insertNode;
if (head->next == head) {
head->next = insertNode;
insertNode->next = head;
return head;
}
Node *cur = head;
while (cur->next != head) {
if (insertVal >= cur->val && insertVal <= cur->next->val)
break;
if (cur->val > cur->next->val) {
if (insertVal > cur->val || insertVal < cur->next->val)
break;
}
cur = cur->next;
}
insertNode->next = cur->next;
cur->next = insertNode;
return head;
}
};
- 时间复杂度:
- 空间复杂度:
总结
快乐的链表模拟题,有一次感觉不至于中等……
【今天么的rust可写,赶紧去肝论文了。】
| 欢迎指正与讨论! |