Java循环单链表


/**
 * 循环链表
 */

public class CycleLinkedList
{
    private static final String TAG = "CycleChain";
    private int size = 0;
    private LinkedNode head = null;//头结点,相当于一个标签而已,不是链表众多节点的一部分
    private LinkedNode cur = null;//记录插入之前时候的head的位置

    class LinkedNode
    {
        Object value;
        LinkedNode next = null;

        LinkedNode(Object obj)
        {
            this.value = obj;
        }
    }

    public boolean isEmpty()
    {
        return size == 0;
    }

    public int getSize()
    {
        return size;
    }

    public void insertHead(Object obj)
    {
        LinkedNode node = new LinkedNode(obj);
        if (head == null)
        {
            node.next = head;
            head = node;
            cur = head;
            head.next = head;
        } else
        {
            while (head.next != cur)
            {
                head = head.next;
            }
            head.next = node;
            head = node;
            head.next = cur;
            cur = head;
        }
        size++;
    }

    public void deleteHead() throws Exception
    {
        if (head == null) throw new Exception("空链表!");
        while (head.next != cur)
        {
            head = head.next;
        }
        cur = cur.next;
        head.next = cur;
        head = cur;
    }

    public void display() throws Exception
    {
        if (head == null) throw new Exception("空链表!");
        LinkedNode cur = head;
        int i = 0;
        while (cur != null && i < getSize() * 4)
        {
            System.out.print(cur.value.toString() + "->");
            cur = cur.next;
            i++;
        }
        System.out.println("");
    }

    public static void main(String[] args) throws Exception
    {
        CycleLinkedList cc = new CycleLinkedList();
        cc.insertHead("哈哈");
        cc.insertHead("ds");
        cc.insertHead("123123你好");
        cc.insertHead("ggt");
        cc.display();
        System.out.println("---");
        cc.deleteHead();
        cc.deleteHead();
        cc.insertHead("test!");
        cc.display();
        System.out.println("---");

        System.out.println(cc.getSize());

    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值