完整代码实例-借助头结点和尾指针实现简单的单向循环链表(Java)

代码如下:

package DataStrcture.ArrayDemo.circlesinglelistdemo;

public class CircleSingleListDemo {
    ///结点类
    static class Node{
        Node next;
        int num;

        public Node(int num){
            this.num = num;
        }

        public String toString(){
            return "num= "+num;
        }
    }
    ///头结点和尾指针
    Node head = new Node(0);
    Node temp = head;

    ///添加结点
    public  void  add(Node node){
    ///因为temp是尾指针, 始终指向此循环链表的最后一个并且temp指针的下一个节点永远是head结点!
    //所以我们不需要下面注释掉的这部分判断.
//        while(true){
//            temp = temp.next;
//            if(temp.next == head)
//                break;
//
//        }
        temp.next = node;
        temp = node;
        temp.next = head;
    }

    //打印输出
    public void list(){
        ///temp.next = head;
        ///临时结点
        Node first = head;
        while(true){
            if( first.next == head)
                break;
            first = first.next;
            System.out.println(first);
        }
    }

    测试类
    public static void main(String[] args) {
        CircleSingleListDemo cl = new CircleSingleListDemo();
        
         Node node_1 = new  Node(6);
         Node node_2 = new  Node(1);
         Node node_3 = new  Node(7);
         Node node_4 = new  Node(2);
         Node node_5 = new  Node(9);
         Node node_6 = new  Node(5);
         Node node_7 = new  Node(12);
         Node node_9 = new  Node(79);
         Node node_10 = new  Node(80);

         cl.add(node_1);
        cl.add(node_2);
        cl.add(node_3);
        cl.add(node_4);
        cl.add(node_5);
        cl.add(node_6);
        cl.add(node_7);
        cl.add(node_9);
        cl.add(node_10);

        cl.list();

    }
}


执行结果:

在这里插入图片描述

在这里插入图片描述

posted @ 2022-05-26 20:31  青松城  阅读(50)  评论(0编辑  收藏  举报