循环链表

通常链表都是一条龙,现在首尾相连,使得从结尾又能一下子跳回到开头,这就是循环链表

这里从以下几个方面阐述循环链表:

  1. 重要方法分析
  2. 全部代码
一.重要方法分析

这里的链表实现了我博客中的接口 ILinkedList 与结点 LinkedNode ,具体的博客地址:http://blog.csdn.net/weixin_35757704/article/details/77894325

void insert(int key):

int delete():

boolean isEmpty():


二.全部代码
package com.list;

/**
 * 循环链表:
 * head -> 1 -> 2 -> 3 -> 4 -> 1 -> ...
 * 这样,从 4向后指,就直接返回到了1,而 1.next又是 2 ,形成循环
 * 因此最后一个节点的 next = head.next 就好
 * 注意这样的链表中没有 prev (指向前一个元素)指针
 */
public class CircularList implements ILinkedList {

    LinkedNode head;
    int count;  //记录节点个数,因为此时寻找最后一个元素时不能通过 node.next == null 来判断

    @Override
    public void insert(int key) {
        LinkedNode node = new LinkedNode(key);
        if (!isEmpty()) {
            //将新节点添加入链表中
            node.next = head.next;
            head.next = node;
            //更新最后一个节点的 next
            LinkedNode temp = new LinkedNode(0);
            temp.next = head.next;
            for (int i = 0; i <= count; i++) {
                temp = temp.next;
            }
            temp.next = head.next;
        } else {
            head.next = node;
            node.next = head.next;
        }
        count++;
    }

    @Override
    public int delete() {
        assert !isEmpty();
        LinkedNode p = new LinkedNode(0);
        p.next = head.next;
        int key = 0;
        for (int i = 0; i < count - 1; i++) {
            //现在 p.next.next 为 null,即 p -> p.next -> null ,现在要删除 p.next , 同时满足循环链表的性质
            p = p.next;
        }
        key = p.next.key;
        count--;
        return key;
    }

    @Override
    public boolean isEmpty() {
        return head.next == null;
    }

    public CircularList() {
        count = 0;
        head = new LinkedNode(0);
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值