带头循环单链表相较于不带头非循环单链表而言,下图给出了它的示意图,可以看出:它多了一个头结点,还有既然它是循环的,那么它的尾节点就不再指向null
了,而是指向头结点。
- 以下是带头循环单链表的
Java
语言实现:
package com.circlelinked;
public interface ICLinked {
//头插法
void addFirst(int data);
//尾插法
void addLast(int data);
//任意位置插入,第一个数据节点为0号下标
boolean addIndex(int index, int data);
//查找是否包含关键字key是否在单链表当中
boolean contains(int key);
//删除第一次出现关键字为key的节点
int remove(int key);
//删除所有值为key的节点
void removeAllKey(int key);
//得到单链表的长度
int getLength();
//打印单链表
void display();
//清空单链表以防内存泄漏
void clear();
}
package com.circlelinked;
public class CHeadSingleListImpl implements ICLinked {
class Node {
private int data;
private Node next;
public Node() {
this.data = -1;
this.next = null;
}
public Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
public CHeadSingleListImpl() {
this.head = new Node();
this.head.next = this.head;
}
@Override
public void addFirst(int data) {
Node node = new Node(data);
node.next = this.head.next;
this.head.next = node;
}
@Override
public void addLast(int data) {
Node node = new Node(data);
Node cur = this.head;
while (cur.next != this.head) {
cur = cur.next;
}
node.next = cur.next;
cur.next = node;
}
@Override
public boolean addIndex(int index, int data) {
Node cur = this.head;
if(index < 0 || index > getLength()) {
return false;
}
for (int i = 0; i < index; i++) {
cur = cur.next;
}
//cur就是index位置的前驱
Node node = new Node(data);
node.next = cur.next;
cur.next = node;
return true;
}
@Override
public boolean contains(int key) {
Node cur = this.head.next;
while (cur != this.head) {
if (cur.data != key) {
cur = cur.next;
}
return true;
}
return false;
}
private Node searchPre(int key) {
Node pre = this.head;
while (pre.next != this.head) {
if (pre.next.data != key) {
pre = pre.next;
}
return pre;
}
return null;
}
@Override
public int remove(int key) {
Node pre = searchPre(key);
int oldData = 0;
if(pre == null) {
throw new Error();
}
oldData = pre.next.data;
pre.next = pre.next.next;
return oldData;
}
@Override
public void removeAllKey(int key) {
if (this.head == null || this.head.next == this.head) {
return;
}
Node pre = this.head;
Node cur = this.head.next;
while (cur != this.head) {
if (cur.data == key) {
pre.next = cur.next;
cur = cur.next;
}else {
pre = cur;
cur = cur.next;
}
}
}
@Override
public int getLength() {
//头结点不算
Node cur = this.head.next;
int count = 0;
while (cur != this.head) {
count++;
cur = cur.next;
}
return count;
}
@Override
public void display() {
Node cur = this.head.next;
while (cur != this.head) {
System.out.print(cur.data + " ");
}
System.out.println();
}
@Override
public void clear() {
while (this.head.next != this.head) {
Node cur = this.head.next;
this.head.next = cur.next;
}
this.head = null;
}
}