Java单链表

来源:互联网 发布:c语言分隔符 编辑:程序博客网 时间:2024/05/22 03:16
public class LinkedList{    /*自带的数据结构*/    /*需要有一个头结点,然后还有一个长度,没有头结点无法查询,     * 对象本身其实就带有一个指针,然后顺则对象给出来的地址,和头结点,才能找到其他的节点!    **/    private int size = 0;    private LinkedListNode header = null;    class LinkedListNode    {        Object value;        LinkedListNode next = null;        LinkedListNode(Object v)        {            this.value = v;        }    }    public boolean isEmpty()    {        return size == 0;    }    public int getSize()    {        return size;    }    public void insertHead(Object obj)    {        LinkedListNode node = new LinkedListNode(obj);        node.next = header;        header = node;        size++;    }    public void deleteHead() throws Exception    {        if (header == null)        {            throw new Exception("空链表无法删除!");        } else        {            header = header.next;            size--;        }    }    public void display() throws Exception    {        if (header == null) throw new Exception("空链表");        LinkedListNode cur = header;        while (cur != null)        {            System.out.print(cur.value.toString() + "->");            cur = cur.next;        }        System.out.println("");    }    public static void main(String[] args) throws Exception    {        LinkedList ch = new LinkedList();        ch.insertHead("1");        ch.insertHead("2");        ch.insertHead("ppp");        ch.insertHead("1gg");        ch.insertHead("tt");        ch.insertHead("zhongguo");        ch.display();    }}
0 0
原创粉丝点击