java - 来自不同类节点的链表

标签 java data-structures linked-list

我正在尝试为一个模拟杂货市场篮子的作业创建一个链表,其中篮子是链表,其中的节点(链接)是每个产品。下面的代码代表购物篮(LinkedList)和一些产品 Gouda 和 Bacon。我的问题是如何从这两个节点创建一个链表,以便我可以获得像 Gouda->Bacon->Bacon->Gouda 等 LinkedList?

提前谢谢你

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

这就是子类和继承的基本思想。

关于java - 来自不同类节点的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064589/

相关文章:

java - Vaadin Crud 用户界面。轴排序不正确

java - 运行时在 build.gradle 之外的 Gradle 项目版本

c - 链表插入中的 strcmp 导致程序崩溃

c - C语言从另一个链表填充空链表

c - 为什么这段 C 代码会在 macOS 上生成段错误,而在其他系统上不会?

创建节点链接列表

java - JAXB:是否可以在没有@XmlJavaTypeAdapter 的情况下使用XmlAdapter?

java - 无法创建 Java VM --- 如何获得更详细的错误消息?

algorithm - 在通用数据结构方面,如何高效地列出树数据结构中节点下的所有叶子?

data-structures - B 树中的最大和最小键数