我正在使用Java中的单链表实现deque。我的addFirst()
功能正常,但addLast()
无效。
每当我拨打addLast()
时,都会收到以下错误消息:
显示java.lang.NullPointerException
答案 0 :(得分:1)
你的上一次是npm install
。
将其分配给import UIKit
import Foundation
func firstTask() -> Bool {
// Do something
print("First task")
return true // change this to determine the task success or not
}
func secondTask() -> Bool {
// Do something
print("Second task")
return true // change this to determine the task success or not
}
func thirdTask() {
// Do something
print("Third task")
}
let thirdBlock: (_ success: Bool) -> () = { success in
guard success else { return }
thirdTask()
}
let secondBlock: (_ success: Bool) -> () = { success in
guard success else { return }
let success = secondTask()
thirdBlock(success)
}
let firstBlock: () -> () = {
let success = firstTask()
secondBlock(success)
}
firstBlock()
时,null
也为空。
因此,当您致电old_last
时,old_last
会抛出。
答案 1 :(得分:0)
为Node类提供构造函数将有助于保持代码简短和干燥:
private class Node {
Item item;
Node next;
private Node(Item item, Node next) {
if (item == null) throw new NullPointerException();
// 'this' refers to the created instance and helps distinguish the field from the param
this.item = item;
this.next = next;
}
}
public void addFirst(Item item) {
// creates a new Node before first so to speak and then repoints first to this node
first = new Node(item, first);
if (num_elements==0) last = first;
num_elements++;
}
public void addLast(Item item) {
if (num_elements == 0) {
// this will deal with the case (last==null) which causes the NPE
addFirst(item);
return;
}
last.next = new Node(item, null);
last = last.next;
num_elements++;
}
除此之外,单链表不是双端队列的理想数据结构。在两端添加O(1)
时,从后面删除O(N)
!