循环单链表
循环单链表是另一种形式的链式存储结构,它的特点是表中的最后一个结点的指针域指向头结点,整个链表形成一个环;
循环单链表与单链表的差别仅为单链表尾结点的指针域为null,循环单链表最后一个数据节点指向的是头结点;
写法差别不是很多,只需要注意最后一个结点的指向就好啦
也可以参考单链表的相关知识,点击单链表常用方法、单链表相关面试真题
class Clink {
class Entry {
int data;
Entry next;
public Entry() {
this.data = -1;
this.next = null;
}
public Entry(int val) {
this.data = val;
this.next = null;
}
}
private Entry head;
public Clink() {
this.head = new Entry();
this.head.next = this.head;//头结点的next指向自己
}
//头插法
public void insertHead(int val) {
Entry entry = new Entry(val);
entry.next = this.head.next;
this.head.next = entry;
}
//尾插法
public void insertTail(int val) {
Entry entry = new Entry(val);
Entry cur = this.head;
while (cur.next != this.head) {
cur = cur.next;
}
cur.next = entry;
entry.next = this.head;
}
//删除所有值为value的节点
public void deleteVal(int val) {
Entry pre = this.head;
Entry cur = this.head.next;
while (cur != this.head) {
if (cur.data != val) {
pre = pre.next;
cur = cur.next;
} else {
pre.next = cur.next;
cur = pre.next;
}
}
}
//打印
public void show() {
Entry cur = this.head.next;
// 最后一个数据节点的next指向的是头结点
while (cur != this.head) {
System.out.print(cur.data + " ");
cur = cur.next;
}
System.out.println();
}
}