循环链表构建
循环链表与链表区别就在于尾指针不再指向null而是指向头指针,形成环。
接口定义:
package p1.接口;
import java.util.Comparator;
public interface List<E> extends Iterable<E> {
public void add(E element);//在表尾添加
public void add(int index, E element);//指定位置添加
public void remove(E element);
public E remove(int index);//删除指定角标元素
public E get(int index);
public E set(int index, E element);//修改
public int size();//返回元素总个数
public int indexOF(E element);//元素查角标
public boolean contains(E element);//是否包含
public boolean isEmpty();
public void clear();
public void sort(Comparator<E> c);
public List<E> subList(int formIndex, int toIndex);
}
单链表的实现:
package p3.链式结构;
import p1.接口.List;
import java.util.Comparator;
import java.util.Iterator;
//单向循环链表
public class LinkedSinglyCircularList<E> implements List<E> {
//定义结点对象
private class Node {
E data; //数据域
Node next; //指针域
public Node(){
this(null,null);
}
public Node(E data) {
this(data,null);
}
public Node(E data, Node next) {
this.data = data;
this.next = next;
}
@Override
public String toString() {
return data.toString();
}
}
private Node head; //头指针
private Node tail; //尾指针
private int size; //元素的个数
//构造函数
public LinkedSinglyCircularList() {
head = null;
tail = null;
size = 0;
}
public LinkedSinglyCircularList(E[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("arr is null");
}
for (int i = 0; i < arr.length; i++) {
add(arr[i]);
}
}
//实现类中的方法
//在末尾添加元素
@Override
public void add(E element) {
add(size, element);
}
//在某一下标处添加元素
@Override
public void add(int index, E element) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("add index out of range");
}
Node n = new Node(element);
if (size == 0) {
//添加时表中没有元素
head = n;
tail = n;
tail.next = head;
} else if (index == 0) {
//在表头添加元素
n.next = head;
head = n;
tail.next = head;
} else if (index == size) {
//在表尾添加元素
n.next = tail.next;
tail.next = n;
tail = n;
} else {
//在中间添加元素
Node p = head;
for (int i = 0; i < index - 1; i++) {
p = p.next;
}
n.next = p.next;