创建单链表

来源:互联网 发布:科比职业生涯场均数据 编辑:程序博客网 时间:2024/05/17 06:13

public class Lnode {
    public String key;
    public Lnode next;
    
    public Lnode(String key)
    {
        this.key=key;
        this.next=null;
    }
    
    public Lnode(String key,Lnode next)
    {
        this.key=key;
        this.next=next;
    }
    public String getKey()
    {
        return key;
    }
}



import org.omg.CORBA.PUBLIC_MEMBER;



public class MyList {

    private Lnode head=null;
    private Lnode tail=null;
        
    public void initiate(Lnode node)
    {
        head=node;
        head.next=tail;
    }

    public void addToList(Lnode node) {
        if (head == null) {
            initiate(node);
        }
        else{
            Lnode tmp = head;
            head = node;
            node.next = tmp;
        }
    }
    
    public Lnode getHead() {
        return head;
    }
    
    public void print(MyList myLisTest)
    {
        Lnode tmp=null;
        for (tmp=myLisTest.getHead();tmp!=null;tmp=tmp.next) {
            System.out.print(tmp.getKey());
        }
    }
    public static void main(String[] args)
    {
        System.out.println("begin");
        MyList myList = new MyList();
        Lnode node1 = new Lnode("1");    
        Lnode node2 = new Lnode("2");
        System.out.println("can can new node");
        myList.addToList(node1);
        myList.addToList(node2);
        System.out.println("can add node");
        myList.print(myList);
        
    }
}




0 0
原创粉丝点击