**
单向循环链表
**
对于单链表而言,最后一个结点指针域是空指针,如果将该链表头指针置入该指针域,则使得链表头尾结点相连,这就构成了单循环链表。和单链表的操作基本相同,只是把最后一个结点的指针域指向头指针而已,其他没有变化。上篇博文我们说单链表有个缺点,就是无法随机查找,每次查找一个结点都要从头开始,那么单循环链表就很好地解决掉了这个问题。单循环链表可以从表中任意结点开始遍历整个链表。
代码如下:
class LoopSingleLinkedList<E>{
protected Node<E>head;
class Node<E>{
protected E data;
protected Node<E>next;
public Node(E data){
this.data=data;
}
}
public void add(E data){
Node<E> newNode =new Node(data);
//链表为空
if (head==null){
head=newNode;
newNode.next=head;
}
Node<E>tail =head;
while (tail.next!=head){
tail=tail.next;
}
newNode.next=tail.next;
tail.next=newNode;
}
public boolean remove(E data){
if (head.data==data){
Node<E>tail=head;
while (tail.next !=head){
tail=tail.next;
}
head=head.next;
tail.next=head;
return true;
}
Node<E>prev =head;
Node<E>current=head.next;
while (current !=head){
if (current.data==data){
prev.next=current.next;
current=null;
return true;
}
prev=current;
current=current.next;
}
return false;
}
public void show(){
Node<E> current =head;
while (current.next !=head){
System.out.println(current.data+ " ");
current=current.next;
}
System.out.println(current.data+ " ");
System.out.println();
}
}