Вы собираетесь ДОЛЖНЫ использовать ... подождите ... РЕКУРСИЯ!
Вот пример со связанным списком
public Node<E> go_deep(Node<E> nodeRef) {
// base case
if(nodeRef.next == NULL)
return nodeRef;
return go_deep(nodeRef.next);
}
Тогда вы можете получить "last "node by:
public static void main(String[] args) {
Node<E> lastNode = go_deep(head);
}
Где head - ваш первый элемент (в данном случае вектор).У вас могут быть разные методы для следующего и предыдущего тоже ...
Я пишу это изо всех сил, и вам нужно определить узел, если вы действительно хотите, чтобы это работало, это просто основнойidea ...
Если Vector (узел в моем примере) не передается по ссылке:
// if you have two-way references
public static void main(String[] args) {
Node<E> lastNode = go_deep(head); //returns the last Node
Node<E> prevNode = lastNode.prev; //returns the Node before
Node<E> newNode = new Node<E>();
// update newNode with lastNode's values
newNode.foo = lastNode.foo;
newNode.bar = lastNode.bar + 7;
prevNode.next = newNode; //newNode is inserted into the structure - lastNode dies :(
}
Если у вас есть односторонние ссылки, мы модифицируем go_deep для возврата массиваузел и его родитель:
public Node<E>[] go_deep(Node<E> nodeRef) {
// base case
// THERE ARE EDGE CASES THAT I'M IGNORING BECAUSE I'M NOT PROGRAMMING FOR YOU!
if(nodeRef.next.next == NULL) {
Node<E>[] arr = new Node<E>[2];
arr[0] = nodeRef; // the "prev" node
arr[1] = nodeRef.next; // the "last" node
return arr;
}
return go_deep(nodeRef.next);
}
затем в основном:
public static void main(String[] args) {
Node<E>[] nodes = go_deep(head); //returns the array of nodes
Node<E> lastNode = nodes[1]; // returns the last Node
Node<E> prevNode = nodes[0]; //returns the Node before
Node<E> newNode = new Node<E>();
// update newNode with lastNode's values
newNode.foo = lastNode.foo;
newNode.bar = lastNode.bar + 7;
prevNode.next = newNode; //newNode is inserted into the structure - lastNode dies :(
}