[英]Circular Single Linked List
我一直在嘗試用Java創建循環鏈接列表。 我相信自己已正確插入,但無法刪除或顯示其正常工作。 這是我的代碼。
public class Link
{
public int data;
public Link next;
public Link(int d)
{
data = d; //store data
next = null; //set next Link to newLink
}
}
public class IntListCircularCount
{
private Link first;//this always points to the first link.
private Link current=null;
private int count =0;
public IntListCircularCount()
{
first = null;
}
public boolean isEmpty()
{
return (first==null);
}
public Link getFirst()
{
return first;
}
public void insert(int n)
{
if(count == 0)
{
Link newLink = new Link(n);
first=newLink;
count++;
current = first;
}
else if(count>0)
{
Link newLink = new Link(n);
first.next = newLink;
newLink.next = first;
count++;
current = first.next;
}
}
public void display(int width)
{
if(isEmpty())
System.out.printf("%" + width + "s", "--");
else if(count ==1)
System.out.printf("%" + width + "d",first.data);
else if(!isEmpty() && first.next !=first)
{
while (first !=current)
{
System.out.printf("%" + width + "d", current.data);
current = current.next;
}
}
}
public void delete()
{
if(count==0)
{
first=null;
}
else if(count==1)
{
first = first.next;
}
else if(count>1)
{
current.next=first.next;
first = first.next;
count--;
}
}
}
public class IntListUser
{
public static void main (String[] args)
{
final int n =5;//there will be n Links
final int w=5; //field width for display
IntListCircularCount list = new IntListCircularCount();
for(int i=1; i<=n; i++)
{
list.display(w);
list.insert(10*i);
}
list.display(w);
System.out.println(" -------------end of inserting ----------------");
list.delete();
list.display(w);
list.delete();
list.display(w);
list.delete();
list.display(w);
list.delete();
list.display(w);
list.delete();
list.display(w);
}
}
我通常在編寫任何代碼之前先做一些草稿草圖。 他們為我省了很多麻煩。
好的,但是您的問題是:
您的插入僅在第一個元素之后插入。 如果當前指向末尾,則在插入新元素時應將其鏈接到當前,而不是第一個。 即使只有一個元素,current也應始終指向第一個(使列表成為圓形)。
public void insert(int n)
{
if(count == 0)
{
Link newLink = new Link(n);
first=newLink;
count++;
current = first;
current.next = first;
}
else
{
Link newLink = new Link(n);
current.next = newLink;
newLink.next = first;
count++;
current = current.next;
}
}
另外,您的顯示需要從第一顯示到最新顯示,但您不應失去第一和最新顯示。
public void display(int width)
{
Link display_me = first;
if(isEmpty())
System.out.printf("%" + width + "s", "--");
else
{
Link display_me = first;
do {
System.out.printf("%" + width + "d", current.data);
display_me= display_me.next;
} while (first != display_me);
}
}
至於刪除,我不知道您要刪除第一個還是當前的。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.