0
我一直在嘗試在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);
}
}
描述你期望你的代碼做什麼,它實際上做了什麼。 – occulus 2011-04-01 00:43:50
我需要它從插入的第一項中刪除,我需要它來顯示剩下的元素的順序。現在它似乎刪除第一個,然後跳轉到最後一個元素。 – Marie 2011-04-01 01:15:15
好的,插入方法應該做什麼?在列表的頭部插入一個新項目?或者把它放在最後?另外,「當前」應該指向什麼?列表中的最後一項? – occulus 2011-04-01 11:01:53