题目:
在一个循环链表中节点的值递增排序,请设计一个算法在该循环链表中插入节点,并保证插入节点之后的循环链表仍然是排序的。插入节点4如图:
分析:
循环链表是一种特殊形态的链表,它的所有节点都在一个环中,在解决与循环链表相关的题中需要注意避免死循环,遍历链表时等所有节点都遍历完就要停止,不能一直在里面绕圈子出不来。
该题通常情况,在相邻的两个节点中插入,前一个节点的值一定小于该节点的值,后一个节点一定大于该节点的值,也要讨论特殊情况,例如图中的6 》1,能插入这两个节点中间要么比链表中谁的值都大,要么比链表中谁的值都小,因此类似这种情况就得特殊对待了,还需要注意链表为空,链表只有一个节点这种情况,循环链表考虑的东西有点多,所以不要遗漏。
public class InsertCore {
public static Node insert(Node head,int insertval){
Node node = new Node(insertval);
if (head == null){
head = node;
head.next = head;
}else if (head.next == head){
head.next = node;
node.next = head;
}else {
insertCore(head,node);
}
return head;
}
private static void insertCore(Node head, Node node) {
Node cur = head;
Node next = head.next;
//biggest节点是用来寻找循环链表中值最大的节点的
Node biggest = head;
while (!(cur.val <= node.val && next.val >= node.val )&& next !=head){
cur = next;
next = next.next;
if (cur.val >= biggest.val){
biggest = cur;
}
}
if (cur.val <= node.val && next.val >= node.val){
cur.next = node;
node.next = next;
}else {
node.next = biggest.next;
biggest.next = node;
}
}
}