通常链表都是一条龙,现在首尾相连,使得从结尾又能一下子跳回到开头,这就是循环链表
这里从以下几个方面阐述循环链表:
- 重要方法分析
- 全部代码
一.重要方法分析
这里的链表实现了我博客中的接口 ILinkedList 与结点 LinkedNode ,具体的博客地址:http://blog.csdn.net/weixin_35757704/article/details/77894325
void insert(int key):
![](https://img-blog.csdn.net/20170908144851407)
int delete():
![](https://img-blog.csdn.net/20170908144935178)
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);
}
}