簡體   English   中英

來自不同類節點的鏈表

[英]Linked list from different class nodes

我正在嘗試為一種模擬雜貨市場的籃子的任務創建一個鏈表,其中籃子是鏈表,其中的節點(鏈接)是每個產品。 下面的代碼代表籃子(LinkedList)和一些產品 Gouda 和 Bacon。 我的問題是如何從這兩個節點中創建一個鏈表,以便獲得像 Gouda->Bacon->Bacon->Gouda 等的 LinkedList?

ps先謝謝你

public class Test {
    public static void main(String[] args) {
    LinkedList theLinkedList = new LinkedList();
    theLinkedList.insertFirstLink();
    theLinkedList.display();
   }
}

class LinkedList{

// Reference to first Link in list
// The last Link added to the LinkedList

public Gouda firstLink; 

LinkedList(){

    // Here to show the first Link always starts as null

    firstLink = null;

}

// Returns true if LinkList is empty

public boolean isEmpty(){

    return(firstLink == null);

}

public void insertFirstLink(){

    Gouda newLink = new Gouda();

    // Connects the firstLink field to the new Link 

    newLink.next = firstLink;

    firstLink = newLink;

}


public void display(){

    Gouda theLink = firstLink;

    // Start at the reference stored in firstLink and
    // keep getting the references stored in next for
    // every Link until next returns null

    while(theLink != null){

        theLink.display();

        System.out.println("Next Link: " + theLink.next);

        theLink = theLink.next;

        System.out.println();

    }

    }
}

public class Gouda{

// Set to public so getters & setters aren't needed

    public String category= "Dairy";
    public String productName = "Gouda Cheese";
    public double price = 57.50;

    // Reference to next link made in the LinkList
    // Holds the reference to the Link that was created before it
    // Set to null until it is connected to other links

    public Gouda next; 

    public void display(){

        System.out.println(category+" :"+ productName +""+ price);

    }   
}

public class Bacon{

// Set to public so getters & setters aren't needed

    public String category= "Meat";
    public String productName = "Thick cut Bacon";
    public double price = 5.50;

    // Reference to next link made in the LinkList
    // Holds the reference to the Link that was created before it
    // Set to null until it is connected to other links

    public Bacon next; 

    public void display(){

        System.out.println(category+" :"+ productName +""+ price);

    }   
}

您應該定義一個新類,例如Product ,將GoudaBacon定義為它的子類。

然后在鏈表中定義 firstLink 為:

public Product firstLink; 

並始終在類LinkedList使用 Product 。 通過這種方式,您可以在列表中插入GoudeBacon兩個實例,因為它們是Product

這是子類和繼承的基本思想。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM