样例
环形有序链表:1 2 4,插入 3,结果为:1 2 3 4
java代码
/**
* @Description:向有序环形单链表中插入新节点
* @Author: lizhouwei
* @CreateDate: 2018/4/7 11:19
* @Modify by:
* @ModifyDate:
*/
public class Chapter2_18 {
public Node insertNum(Node head, int value) {
Node pre = head;
Node cur = head.next;
while (cur != head) {
if (pre.vlaue < value && value < cur.vlaue) {
break;
}
pre = cur;
cur = cur.next;
}
Node node = new Node(value);
pre.next = node;
node.next = cur;
return head.vlaue < value ? head : node;
}
public void print(Node head) {
System.out.print(head.vlaue + " ");
Node pre = head;
Node cur = head.next;
while (cur != head) {
System.out.print(cur.vlaue + " ");
cur = cur.next;
}
}
//测试
public static void main(String[] args) {
Chapter2_18 chapter = new Chapter2_18();
Link link = new Link();
//构造链表
for (int i = 10; i > 0; i--) {
link.add(i);
}
Node node2 = new Node(2);
Node node4 = new Node(4);
Node node1 = new Node(1);
node1.next = node2;
node2.next = node4;
node4.next = node1;
chapter.print(node1);
Node head = chapter.insertNum(node1, 3);
chapter.print(head);
}
}