循环链表
Posted ssdut_yrp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环链表相关的知识,希望对你有一定的参考价值。
public class Link
public long lData;
public Link next;
public Link(long lData)
this.lData=lData;
public void displayLink()
System.out.print(lData+" ");
public class CircleList
private Link current;
private int nItems;
public CircleList()
current=null;
public void insert(long value)
Link newLink = new Link(value);
if(current==null)
current=newLink;
newLink.next=newLink;
else
newLink.next=current.next;
current.next=newLink;
current=newLink;//插入元素,current要移动要新元素
nItems++;
public long remove()
long temp = current.next.lData;
if(current.next==current)
current=null;
else
current.next=current.next.next;
nItems--;
return temp;
public long peek()
return current.next.lData;
public Link find(long value)
Link temp =current;
Link result=null;
if(current==null)
return result;
do
step();//从current的下一个元素开始
if(current.lData==value)
result=current;
current=temp;//还原current到原来的位置,这样就不会打乱插入的顺序,current指向最后插入的元素
while(current!=temp);//current到原来的位置,一周循环结束
return result;
public void step()
if(current!=null)
current=current.next;// 调用step()方法后,顺序会被打乱
public void display()
if(current!=null)
Link temp =current;
do
step();// 从current的一下个开始显示
System.out.print(current.lData + " ");
while(current!=temp);
System.out.println();
public boolean isEmpty()
return (current==null);
public int size()
return nItems;
public class CircleListApp
/**
* @param args
*/
public static void main(String[] args)
// TODO Auto-generated method stub
CircleList theCircleList = new CircleList();
theCircleList.insert(10);
theCircleList.insert(20);
theCircleList.insert(40);
theCircleList.insert(30);
theCircleList.display();
System.out.println("最早插入的元素:"+theCircleList.peek());
Link link = theCircleList.find(40);
if(link!=null)
System.out.println("find 40");
else
System.out.println("Can't find 40");
long aLink = theCircleList.remove();
System.out.println("Deleted "+aLink);
theCircleList.display();
以上是关于循环链表的主要内容,如果未能解决你的问题,请参考以下文章