愤怒中的小草

博客园 首页 新随笔 联系 订阅 管理
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();
    }
}

 

posted on 2019-04-28 20:54  愤怒中的小草  阅读(198)  评论(0编辑  收藏  举报