我在创建将项目添加到Java中的最后一个元素之前的方法时遇到了麻烦。我已经有了在链表中添加最后一个元素的代码。
我应如何实施addBeforeLast
?
public class LinkedList {
Node first;
int size = 0;
public void addLast(int item) {
// If the list is empty, just create a node and make it
// the first.
if(first == null) {
first = new Node(item, null);
} else {
// Otherwise, find the last node
Node current = first;
// Stop when current's next is null: that's how
// we know it's the last element.
while(current.next != null) {
current = current.next;
}
Node prev = current;
// At this point, current is the last node.
// Make it point to a new node that will contain
// the given item.
current.next = new Node(item, prev);
}
size++;
}
}
答案 0 :(得分:0)
尝试这样:
public void addBeforeLast(int a) {
if (first == null) throw new IllegalStateException("There is no last node"); // we cannot addBeforeLast when there is no last;
if (first.next == null) { // when only single node, we have to update first;
first = new Node(a, first);
return;
}
Node p = first;
while (p.next.next != null) p = p.next; // p.next will be the last node now;
p.next = new Node(a, p.next);
}
节点将具有以下构造函数:
public Node(int theVal, Node theNext) {
this.val = theVal;
this.next = theNext;
}
顺便说一句,即使在addBeforeLast
没有节点的情况下,如果您坚持要添加新节点。您可以使用此方法:
public void addBeforeLast(int a) {
if (first == null || first.next == null) { // we have to update first;
first = new Node(a, first);
return;
}
Node p = first;
while (p.next.next != null) p = p.next; // p.next will be the last node now;
p.next = new Node(a, p.next);
}