前言
当问题杂乱时,可以分类整理,把情况理清楚。
一、案例
二、题解
package com.xhu.offer.offerII;
//排序的循环链表
public class Insert {
//总结:该题考查问题分析拆解并归类。训练分情况讨论。
//总结:有时候用循环需要先提前写一个循环体在外面,导致很不方便,可以用do while去替代。
public Node insert(Node head, int insertVal) {
if (head == null) {
Node root = new Node(insertVal);
root.next = root;
return root;
}
Node res = head;
//遍历找到比它小的节点,或者是下一个节点小于上一个节点值。
//1,只有两种情况可以插入节点,否则都是往后移继续寻找可以插入处。
//第一,节点值在前后节点之间,节点值在头尾之间;
do {
int m = head.val, n = head.next.val;
if (m <= n && insertVal >= m && insertVal <= n) {
Node node = new Node(insertVal);
node.next = head.next;
head.next = node;
return res;
}
if (m > n && (insertVal >= m || insertVal <= n)) {
Node node = new Node(insertVal);
node.next = head.next;
head.next = node;
return res;
}
head = head.next;
} while (res != head);
Node node = new Node(insertVal);
node.next = res.next;
res.next = node;
return node.next;
}
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _next) {
val = _val;
next = _next;
}
}
}
总结
1)该题考查问题分析拆解并归类。训练分情况讨论。
2)有时候用循环需要先提前写一个循环体在外面,导致很不方便,可以用do while去替代。
参考文献
[1] LeetCode 原题