所以我有一个单链表的实现,我正在尝试添加一个方法来报告列表的倒数第二个节点。但是,我不确定是否允许我在 Node 类下编写该方法,然后从单链表类访问它。如果我这样做,我的节点类的实例变量('head' 用作访问倒数第二个方法的变量,但也用作倒数第二个方法的输入。可以吗?下面是我的实现/尝试。
public class SinglyLinkedList {
private static class Node<Integer>{
private Integer element;
private Node<Integer> next;
private Node<Integer> penultimate;
public Node(Integer e, Node<Integer> n) {
element = e;
next = n;
penultimate = null;
}
public Integer getElement() {return element;}
public Node<Integer> getNext(){return next;}
public void setNext(Node<Integer> n) {next = n;}
public Node<Integer> penultimate(Node<Integer> head) {
Node<Integer> current = head;
while(current != null) {
if(head.getNext() == null) {
penultimate = head;
}
else {
current = current.getNext();
}
}
return penultimate;
}
}
private Node<Integer> head = null;
private Node<Integer> tail = null;
private int size = 0;
public SinglyLinkedList() {}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public Integer first() {
if (isEmpty()) {
return null;
}
return head.getElement();
}
public Integer last() {
if(isEmpty()) {
return null;
}
return tail.getElement();
}
public void addFirst(Integer i) {
head = new Node<> (i, head);
if(size == 0) {
tail = head;
}
size++;
}
千万里不及你
绝地无双
相关分类