CircularSinglyList(环型单链表)
代码部分
public class CircularSinglyList<T> {
public Node<T> head; // 创建头结点
//构造函数1,只有一个头结点
public CircularSinglyList() {
this.head = new Node<T>();
}
// 构造函数2,依次将values中的值填入单链表中
public CircularSinglyList(T[] values, T x) {
this(); // 构造一个空的单链表
Node<T> current = this.head;
int d = 3;
Node<T> rear = this.head; // 为空的单链表设置头结点
for (int i = 1; i <= values.length; i++) {
Node<T> node = (Node<T>) new Node<Integer>(i);
current.next = node;
current = node;
}
//有数据的部分首尾相连形成一个环。
current.next = head.next;
remove(d);
}
// 判断单链表是否为空
public boolean IsEmpty() {
return this.head.next == null; // 带头结点的单链表判断为空的条件是头结点以后为空
}
// 删除第i位结点
public void remove(int distance) {
//统计开始从第一个有数据的结点开始
Node<T> p = head.next;
//下一个结点是它本身结束
while (p.next != p) {
//遍历
for (int j = 1; j < distance - 1; j++) {
p = p.next;
}
//出局
System.out.print(p.next.data + "->");
p.next = p.next.next;
p = p.next;
}
System.out.println(p.data);
}
}
写在最后:
仅为学习阶段记录写过的代码,方便自己查找,初出茅庐,有不完善的地方烦请指正,如有继承类可查阅数据结构其他博文。