1 循环链表简介
循环链表的任意元素都有一个前驱和一个后继,所有数据元素在关系上构成逻辑上的环。
循环链表是一种特殊的单链表,尾结点的指针指向首结点的地址。
循环链表的逻辑关系图如图2-1所示:
2 循环链表实现
2.1 API
类名 | LinkList |
---|---|
构造方法 | LinkList() |
成员方法 | 1. public boolean add(E e):添加元素 2. public void add(int index,E e):指定位置添加元素 3. public void clear():清空链表 4. public E get(int index):获取指定索引位置的元素 5. public int indexOf(Object o):返回元素在链表中的位置索引 6. public E remove(int index):删除指定索引位置的元素 7. public boolean remove(Object o):删除链表中的元素 8. public E set(int index,E e):给指定索引位置节点设置值 9. public int size():获取链表的大小 |
成员变量 | 1. private int size:链表大小 2. private Node<E> first:链表头指针 3. private Node<E> last:链表尾指针 |
成员内部类 | 1. private class Itr:迭代器 2. private static class Node<E>:节点类 |
类名 | Itr |
---|---|
构造方法 | Itr(int index) |
成员变量 | 1. private Node<E> lastReturned:上一个返回的节点 2. private Node<E> next:下一个节点 3. private nextIndex:下一个索引 |
成员方法 | 1. public boolean hasNext():是否有下一个节点 2.public E next():下一个节点 3. public void remove():移除当前节点 4. public void forEachRemaing(Consumer<? super E> action) |
2.2 代码
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
/**
* @author Administrator
* @version 1.0
* @description 单向循环链表
* @date 2022-10-24 21:09
*/
public class CircularList<E> {
/**
* 节点类
* @param <E>
*/
private static class Node<E> {
E item;
Node<E> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
private int size;
private Node<E> first;
private Node<E> last;
public CircularList() {}
/**
* 添加元素e
* @param e 目标元素
* @return 添加是否成功
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 插入链表末尾
* @param e 目标元素
*/
private void linkLast(E e) {
Node<E> l = last;
Node<E> newNode = new Node<>(e, null);
last = newNode;
if (l == null) {
first = newNode;
newNode.next = newNode;
} else {
newNode.next = first;
l.next = newNode;
}
size++;
}
/**
* 插入链表头
* @param e 目标元素
*/
private void linkFirst(E e) {
Node<E> f = first;
Node<E> newNode = new Node<>(e, null);
first = newNode;
if (f == null) {
last = newNode;
newNode.next=newNode;
} else {
last.next = newNode;
newNode.next = f;
}
size++;
}
/**
* 指定索引位置插入元素
* @param index 索引
* @param e 目标元素
*/
public void add(int index,E e) {
checkPositionIndex(index);
if (index == size) {
linkLast(e);
} else if (index == 0) {
linkFirst(e);
} else {
linkAfter(e, nodeBefore(index));
}
}
private Node<E> nodeBefore(int index) {
Node<E> x = first;
for (int i = 0; i < index - 1; i++) {
x = x.next;
}
return x;
}
private void linkAfter(E e, Node<E> before) {
// assert before != null;
before.next = new Node<>(e, before.next);
}
private Node<E> node(int index) {
Node<E> x = first;
for (int i = 0; i < index; i++) {
x = x.next;
}
return x;
}
/**
* 检查位置索引是否合法
* @param index 目标索引
*/
private void checkPositionIndex(int index) {
if (!isPositionIndex(index)) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
}
/**
* 检查是否合法的索引
* @param index 目标索引
* @return 是否合法
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/**
* 情况链表
*/
public void clear() {
if (first == null) {
return;
}
last.next = null;
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x = next;
}
first = last = null;
size = 0;
}
/**
* 获取指定索引处的元素
* @param index 目标索引
* @return 指定索引处的元素
*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index)) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* 返回元素在链表中的索引位置
* @param o 目标元素
* @return 目标元素在链表中的索引
*/
public int indexOf(Object o) {
if (size == 0) {
return -1;
}
int index = 0;
if (o == null) {
for (Node<E> x = first; x != last; x = x.next) {
if (x.item == null) {
return index;
}
index++;
}
if (last.item == null) {
return size - 1;
}
} else {
for (Node<E> x = first; x != last; x = x.next) {
if (o.equals(x.item)) {
return index;
}
index++;
}
if (o.equals(last.item)) {
return size - 1;
}
}
return -1;
}
/**
* 移除链表指定索引位置的元素
* @param index 目标索引
* @return 目标索引位置的元素值
*/
public E remove(int index) {
checkElementIndex(index);
if (index == 0) {
return unlinkFirst();
}
return unlink(nodeBefore(index));
}
private E unlinkFirst() {
// assert first != null;
Node<E> f = this.first;
if (size == 1) {
first = last = null;
} else {
last.next = first = first.next;
}
E item = f.item;
f.item = null;
f.next = null;
size--;
return item;
}
private E unlinkLast() {
// assert first != null;
Node<E> l = last;
if (size == 1) {
first = last = null;
} else {
Node<E> prev = nodeBefore(size - 2);
prev.next = first;
last = prev;
}
E item = l.item;
l.item = null;
l.next = null;
size--;
return item;
}
private E unlink(Node<E> prev) {
// assert prev != null && prev.next != null;
Node<E> t = prev.next;
Node<E> next = t.next;
E item = t.item;
t.item = null;
t.next = null;
prev.next = next;
if (next == first) {
last = prev;
}
size--;
return item;
}
/**
* 移除链表中的指定元素
* @param o 目标元素
* @return 是否移除成功
*/
public boolean remove(Object o) {
if (size == 0) {
return false;
}
Node<E> prev = null;
if (o == null) {
for (Node<E> x = first; x != last; x = x.next, prev = x) {
if (x.item == null) {
if (prev == null) {
unlinkFirst();
} else {
unlink(prev);
}
return true;
}
}
if (last.item == null) {
unlinkLast();
return true;
}
} else {
for (Node<E> x = first; x != last; x = x.next, prev = x) {
if (o.equals(x.item)) {
if (prev == null) {
unlinkFirst();
} else {
unlink(prev);
}
return true;
}
}
if (o.equals(last.item)) {
unlinkLast();
return true;
}
}
return false;
}
/**
* 设置指定索引位置元素的值
* @param index 目标位置索引
* @param e 要替换的值
* @return 被替换的旧值
*/
public E set(int index, E e) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = e;
return oldVal;
}
/**
* 返回链表的大小
* @return 链表的大小
*/
public int size() { return size; }
/**
* 判断链表是否为空
* @return
*/
public boolean isEmpty() {
return size == 0;
}
public Iterator<E> iterator() {
return new Itr(0);
}
public Iterator<E> listIterator(int index) {
checkElementIndex(index);
return new Itr(0);
}
@Override
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext()) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext()) {
return sb.append(']').toString();
}
sb.append(',').append(' ');
}
}
private class Itr implements Iterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
public Itr(int index) {
next = node(index);
nextIndex = index;
}
@Override
public boolean hasNext() {
return nextIndex < size;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
@Override
public void remove() {
if (lastReturned == null) {
throw new IllegalStateException();
}
Node<E> prev = node(nextIndex - 1);
if (prev == null) {
unlinkFirst();
} else {
unlink(prev);
}
lastReturned = null;
nextIndex--;
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while ( nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
}
}
}
3 约瑟夫问题
3.1 约瑟夫环解决
Josephu约瑟夫环问题为:设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
3.2 循环链表解决
public static void testJusephus() {
// 初始化链表
int size = 8, start = 5, count = 3;
CircularList<Integer> jusephus = new CircularList<>();
for (int i = 1; i <= size; i++) {
jusephus.add(i);
}
System.out.println("初始数据:" + jusephus);
int index = (start + count - 2);
int[] nums = new int[size];
int i = 0;
int tsize = size;
while (!jusephus.isEmpty()) {
if (index > tsize - 1 ) {
index = index % tsize;
}
int tmp = jusephus.remove(index);
System.out.println(tmp);
nums[i++] = tmp;
index = index + count - 1;
tsize--;
}
System.out.println("出队编号:" + Arrays.toString(nums));
System.out.println("最终数据:" + jusephus);
}
4 后记
如果小伙伴什么问题或者指教,欢迎交流。
❓QQ:806797785
⭐️源代码仓库地址:https://gitee.com/gaogzhen/algorithm
参考:
[1]百度百科.循环链表[EB/OL].2022-09-17/2022-10-08.
[2]黑马程序员.黑马程序员Java数据结构与java算法全套教程,数据结构+算法教程全资料发布,包含154张java数据结构图[CP/OL].p61~p64.