循环单链表

假如想象 提交于 2020-02-24 08:39:09
public class Node {
    public Object data;
    public Node next;

    public Node(){}

    public Node(Object data,Node next){
        this.data = data;
        this.next = next;
    }
}

  

public class CirSingleLink {
    private Node node = null;
    private int size = 0;

    public void init(){
        node = new Node();
        node.data = null;
        //头结点指向头结点
        node.next = node;
    }

    //从尾结点进行插入
    public void add(Object i){
        Node newNode = new Node(i,node);
        if(node.next == node){
            node.next = newNode;
        }else{
            Node tmp = node;
            while (tmp.next != node){
                tmp =tmp.next;
            }
            tmp.next = newNode;
        }

        size ++;
    }

    public void delete(Object i){
        Node tmp = node;
        while(tmp.next != node && tmp.next.data != i){
            tmp = tmp.next;
        }
        tmp.next = tmp.next.next;
    }

    public void display(){
        Node tmp = node.next;
        System.out.println("链表的长度为:" + size);
        while (tmp.next != node){
            System.out.println("打印结点信息:" + tmp.data);
            tmp = tmp.next;
        }
        System.out.println("打印结点信息:" + tmp.data);
    }
}

  

public class Demo {
    public static void main(String[] args){
        CirSingleLink csl = new CirSingleLink();
        csl.init();
        csl.add(1);
        csl.add(2);
        csl.add(3);
        csl.display();
        System.out.println("删除之后的结点信息");
       // csl.delete(2);
        csl.delete(3);
       // csl.delete(1);
        csl.display();
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!