package clink;
//循环单链表
public class TestClink {
public static void main(String[] args) {
// TODO Auto-generated method stub
Clink t1 = new Clink();
for(int i = 0;i<9;i++){
t1.insertHead(i);
}
t1.show();
int len=t1.getlength();
System.out.println(len);
System.out.println("---");
t1.insertTail(5);
t1.insertTail(5);
t1.show();
System.out.println("---");
t1.delete(5);
t1.show();
}
}
class Clink{
class Entry{
int data;
Entry next;
public Entry(){
this.data=-1;
this.next=null;
}
public Entry(int data){
this.data=data;
this.next=null;
}
}
private Entry head=null;
public Clink(){
this.head=new Entry();
this.head.next=this.head;
}
//头插法
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 cur=this.head;//定义一个节点用来寻找链表的尾结点
while(cur.next!=this.head){
cur=cur.next;
}
Entry entry=new Entry(val);//定义要插入的节点
entry.next=cur.next;
cur.next=entry;
}
public boolean isEmpty(){
Entry cur=this.head;
if(cur.next!=this.head){
return false;
}
return true;
}
删除值为5的所有节点
public boolean delete(int val){//此时删除5
Entry prev=this.head;
Entry cur=this.head.next;
if(isEmpty()){
return false;
}
while(cur!=this.head){
if(cur.data==val){
prev.next=cur.next;
cur=prev.next;
}else{
prev=cur;
cur=cur.next;
}
}return true;
}
/*public void delete(int val){
Entry prev=this.head;
Entry cur=this.head.next;
while(cur!=this.head){
if(cur.data==val){
prev.next=cur.next;
cur=prev.next;
}else{
prev=cur;
cur=cur.next;
}
}
}*/
public int getlength(){
Entry cur=this.head;
int len=0;
while(cur.next!=head){
len++;
cur=cur.next;
}
return len;
}
public void show(){
Entry cur=this.head.next;
while(cur!=this.head){
System.out.println(cur.data+"data");
cur=cur.next;
}
System.out.println();
}
}
![]()