package clink; // Circular singly linked list 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 (only); 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; }
//Head insertion method public void insertHead( int val){ Entry entry=new Entry(val); entry.next=this.head.next; this.head.next=entry; }
//Tail insertion method public void insertTail( int val){ Entry cur = this .head; // Define a node to find the end of the linked list while (cur.next!= this .head){ cur=cur.next; } Entry entry = new Entry(val); // Define the node to be inserted entry.next= cur.next; cur.next=entry; } public boolean isEmpty(){ Entry cur=this.head; if(cur.next!=this.head){ return false; } return true; }
Delete all nodes with a value of 5 public boolean delete( int val){//Delete 5 at this time 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 = cure; 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 = cure; 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(); } }
Circular singly linked list in java
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325309602&siteId=291194637
Recommended
Ranking