[英]firstLast Java Linked list/nodes
我对每个节点如何链接到另一个节点感到困惑,以及如何确保如果我希望第一个节点在最后一个节点之后链接,我没有运行无限循环。 例如,在这个问题..
编写一个firstLast方法,可以将其添加到LinkedIntList类中,该类将列表的第一个元素移动到列表的后端。 假设名为list的LinkedIntList变量存储从前(左)到后(右)的以下元素:
[18,4,27,9,54,5,63]如果您调用了list.firstLast();,那么列表将按以下顺序存储元素:
[4,27,9,65,5,63,18]如果列表为空或只有一个元素,则不应修改其内容。
我的第一次尝试就是这样做......但无济于事:
`public void firstLast(){
ListNode temp = front;//stores/references the first node
temp.next = null;//ensures that first node isn't referring to any other
//node
ListNode current = front;//reaches end node/first one with a null
//reference
while(current.next != null){
current = current.next;
}
front.next = temp;//links end node to first node
front = current.next;////now that skips the first element`
但输出是[18] -> [18] (cycles!)
。 请指教
函数firstLast()可以编码如下:
public void firstLast()
{
ListNode temp = removeFirst();
appendLast( temp );
}
所以,现在你把问题分解为两个较小的问题。 这往往是解决任何问题的非常好的策略。
您需要记住的一点是,为了实现您的removeFirst()
,您必须修改front
指向第二个节点,即front.next
。
我对每个节点如何链接到另一个节点感到困惑
在单链表中,每个节点只知道下一个节点。 所以你需要跟踪第一个,通常称为head
(在你的实现中它是“前面”),因为访问所有元素是必不可少的。
...以及如何确保如果我希望第一个节点在最后一个节点之后链接,我没有运行无限循环。
最后一个节点后面没有下一个节点,因此它的next
指针为null
。 您可以使用此条件来避免无限循环。 (只需确保最后一个节点next
正确为null
。)
您的实施可以修复为:
public void firstLast() {
// list is empty or has single element -> nothing to do
if (front == null || front.next == null) {
return;
}
// save the first
ListNode first = front;
// move the head
front = front.next;
// find the end
ListNode current = front;
while (current.next != null) {
current = current.next;
}
// append the node
current.next = first;
// reset the next pointer of the new last node
first.next = null;
}
鉴于您实施:
void push(ListItem item) {
end.next = item;
item.next = null;
}
和
ListItem pop() {
ListItem first = front;
front = front.next;
return first;
}
你的方法变成:
void firstLast() {
push(pop());
}
注意 :未经测试的代码,不检查空值或列表大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.