链表堆栈,推到底部而不是顶部



我正在学习Java中的LinkedLists和堆栈,遇到了一个问题。 目前我有一个推送功能,它将一个对象放在堆栈的顶部。我试图弄清楚如何做相反的事情并将对象推到底部,而不会丢失列表中的链接。

为了帮助您更好地理解我的问题,这里有一些部分。

对象构造函数:

 //Variables
public int planeID;         //unique plane identifier
public String destination;  //destination
public String airline;      //airline name
public String aircraft;     //aircraft type
public double time;         //arrival or departure time
public Plane next;          //next plane in terminal
// Plane Constructor
public Plane (int i, String dest, String airl, String airc, double t) {
        planeID = i;
        destination = dest;
        airline = airl;
        aircraft = airc;
        time = t;
}// END Plane Constructor

插入最后一项(不是工作代码) 已编辑

public void insertLast(int i, String dest, String airl, String airc, double t){//创建新链接 Plane newPlane = new Plane(i, dest, airl, airc, t); 平面温度 = 第一;

while (temp.next != null) {
    temp = temp.next;
}
temp.next = newPlane;
}

最后是推送,其中列表指的是我的 LinkedList:

 public void push(int i, String dest, String airl, String airc, double t) // put item on top of stack
{
    theList.insertLast(i, dest, airl, airc, t);
}

所以,现在我正在尝试创建一个新函数,比如说 insertLast 它将插入元素,最好是列表的底部而不是顶部,所以我可以为此修改我的推送使用队列。

编辑:事实证明,最好为此使用队列。

你在这里拥有的是单链表。如果要将项目插入到此列表的末尾,则必须一直向下,到列表中的最后一项,并将新平面分配给其next参照。列表中的最后一项是null next引用的项目。
或者,作为另一个变体,您可以保留两个链接 - 一个用于列表中的第一项,另一个用于最后一项。这样,当您需要在列表末尾添加某些内容时,您就不需要一直向下。它将是双端列表(不要将其与双重链表混合,这是另一种数据结构)。

当你在学习Java时,我不会只给你代码,所以我写了一些伪代码。

function insertLast(item) {
    tmp = first
    while (tmp.next != null) {
        tmp = tmp.next
    }
    // now we're at the bottom
    tmp.next = item
    item.next = null
}

你要做的是从第一个元素开始,继续获取.next,直到它为 null,然后在列表末尾添加对新对象的引用。