向有序的环形单链表中插入新节点

来源:互联网 发布:大学生艾滋病数据 编辑:程序博客网 时间:2024/06/05 08:21

//向有序的环形单链表中插入新节点public class InsertNode{  //单链表节点的定义    public static class Node{             public int value;       public Node next;       public Node(int data)       {       this.value=data;       }    }    //向有序的环形单链表中插入新节点    public static Node insertNode(Node head,int num)    {    if(head==null)    {    return new Node(num);    }    //(1)开头节点插入新节点,并且构成环形链表    if(head.value>num)    {     Node node=new Node(num);     node.next=head;         Node p=head; //记录先前的头结点    while(head.next!=p)    {    head=head.next;    }    head.next=node; //最后一个节点指向新插入的头节点        return node;    }    //(2)中间插入        Node p=head.next;        Node pre=head; //记录遍历当前节点的前一个节点    while(p!=head)    {    if(p.value<num)    {    pre=p;    p=p.next;    }else    {               //添加节点,直接返回新的链表    Node node=new Node(num);    pre.next=node;    node.next=p;    return head;    }    }    //(3)最后一个节点插入新节点,并且构成环形链表    if(pre.value<=num)    {    Node node=new Node(num);    pre.next=node;    node.next=head;    }    return head;    }   //打印链表的内容    public static void PrintList(Node head)    {      if(head==null)    {    return ;    }    Node p=head;    while(head.next!=null&&head.next!=p)    {        System.out.print(head.value+" ");    head=head.next;    }    System.out.print(head.value+" ");    System.out.println();    }    public static void main(String[]args)    {    //System.out.print("Hello");    //构建环形链表    /**    Node node=new Node(2);node.next=new Node(3);node.next.next=new Node(4);node.next.next.next=node;*///(1)链表为null/*Node node=null;        PrintList(node);        Node mode=insertNode(node,5);        PrintList(mode);       */         //(2)链表开头插入        Node node=new Node(2);node.next=new Node(4);node.next.next=node;PrintList(node);        Node mode=insertNode(node,1);        PrintList(mode);    }}


阅读全文
0 0