[英]Circular Linked List Node Insertion Java
我嘗試為循環鏈表實現insert方法。 我想我取得了一些成功。
問題:當我顯示列表時。 顯示方法將循環,因為鏈接的每個下一個變量都鏈接到非空節點對象。 所以head永遠不會是null對象。 根據我回憶起的單鏈列表,頭總是指向列表中的第一個節點或其中包含數據的第一個節點。
我對圓形鏈表的概念理解:從我的理解中,圓形鏈表有點像單鏈表,但略有不同:尾部對象的下一個變量指向頭部。
我正在對其進行編碼,就像源鏈接提供的圖表一樣。
資料來源: http : //sourcecodemania.com/circular-linked-lists/
public void insert(String data)
{
Link link = new Link(data);
if(head == null)
{
head = link;
tail= link;
}
else
{
tail.next = link;
tail = link;
tail.next = head;
}
}
public void display()
{
// good implementation for display #2
while(head != null)
{
// System.out.println (head.data);
head = head.next;
}
}
一旦插入至少一個元素,就永遠不會遇到null。 它會一直持續到無限遠。
另外,修改head只是為了顯示列表可能不是一個好主意。 像顯示器這樣的操作不應有任何副作用。
相反,請在列表類中保留成員字段的大小,並在每個insert和delete方法中對其進行更新。
現在您將知道應該循環幾次。
ListClassName current = head; // Head is not modified.
for (int i = 0; i < this.size; i++) {
// System.out.println (current.data);
current = current.next;
}
祝好運。
您可以保留對第一個Link對象的引用,並在循環時檢查以確保head不等於該對象:
public void display()
{
boolean first=true;
Link firstItem=null;
// good implementation for display #2
while(head != null && head!= firstItem)
{
if(first){
firstItem=head;
first=false;
}
// System.out.println (head.data);
head = head.next;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.