[程序员代码面试指南]链表问题-向有序的环形链表插入新节点

题意

给定非递减循环链表的头节点,和一个待插入的值,将其插入循环链表。

题解

遍历一遍,找到插入位置则返回;若没找到,说明插到头节点尾节点间,注意区分插入的是最大值还是最小值,返回的头节点不一样。

代码

public class Main {
    public static void main(String args[]) {        
        //test
        Node n1=new Node(1);
        Node n2=new Node(1);
        Node n3=new Node(3);
        n1.next=n2;
        n2.next=n3;
        n3.next=n1;
        Node head=n1;
    
        int num=2;
        head=insertNode(head,num);
        
        //test
        System.out.println(head.val);
        Node pNode=head.next;
        while(pNode!=head) {
            System.out.println(pNode.val);
            pNode=pNode.next;
        }
    }
    
    public static Node insertNode(Node head,int num) {
        Node node=new Node(num);
        if(head==null) {
            node.next=node;
            return node;
        }
        Node pre=head;
        Node cur=head.next;
        while(cur!=head) {
            if(pre.val<num&&cur.val>num) {
                pre.next=node;
                node.next=cur;
                return head;
            }
            pre=pre.next;
            cur=cur.next;
        }
        pre.next=node;
        node.next=cur;
        return node.val<cur.val?node:cur;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/10961578.html
今日推荐