通过万岁!!!
- 题目:给你一个循环链表,链表是非递减的,然后给你一个val,让你找到他应该的位置,进行插入。
- 思路:这个有两种情况,第一种就是我们能够找到一个大于val的,然后下一个小于val,那么直接把他插入到两者之间即可。第二种就是他应该在max之后,或者是在min之前,也就是他是最小的或者最大的。并且这里面有一个判断链表是不是回到原点了,因为变量指向的是内存地址,所以我们直接用==判断即可。
- 技巧:链表的遍历
java代码
class Solution {
public Node insert(Node head, int insertVal) {
Node ans = head;// 最后还是要求返回这个头节点
if (head == null) {
head = new Node(insertVal);
head.next = head;
return head;
}
// 需要考虑在中间,在两端
Node front = head;
Node back = head;
front = front.next;
Node max = head;
while (front != head) {//
if (front.val >= insertVal && back.val <= insertVal) {
back.next = new Node(insertVal, front);
return ans;
}
if (front.val >= max.val) {
max = front;
}
back = front;
front = front.next;
}
// 在尾部和head之间
if (front.val >= insertVal && back.val <= insertVal) {
back.next = new Node(insertVal, front);
return ans;
}
// 在最大值后面插入
front = max.next;
max.next = new Node(insertVal,front);
return ans;
}
}
- 总结:题目不是特别难,主要是有几个特殊情况。