繁体   English   中英

向量中的向量…Java

[英]Vector in Vector… Java

我在向量中有向量。 但我不知道其中有多少(深度是多少)。 如何更改最后一个向量的内容?

您将要使用...等待它...回归!

这是一个带有链表的例子

public Node<E> go_deep(Node<E> nodeRef) {
  // base case
  if(nodeRef.next == NULL)
    return nodeRef;

  return go_deep(nodeRef.next);
}

然后,您可以通过以下方式获取“最后一个”节点:

public static void main(String[] args) {
  Node<E> lastNode = go_deep(head);
}

其中head是您的第一项(在这种情况下为vector)。 您可能对下一个和上一个也有不同的方法...

我是从头开始写的,如果您真的想让它工作,则必须定义一个Node,它只是基本思想...

如果Vector(在我的示例中为Node)未通过引用传递:

// 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 :(
}

作为对塞思的回应,这是您如何使用stac进行操作。 伪代码,可能充满错别字,只是为了描述这个主意...

注意:与递归解决方案存在完全相同的问题,其中反向链接可能导致无限循环。 如果内存不成问题,请保留曾经跟踪过的所有lins的列表(或者在每个项目中标记一个以指示是否遵循),或者如果内存有问题,则使用incr和skip 1的相交循环。 或刚刚设置。 您要遍历的深度的最大值。

// breadth first search to find deepest element
FIND_DEEPEST:
GIVEN tree; // vector of vectors
DECLARE current, previous  // stacks for the current depth and one level up
DECLARW node, children, child // temp vars

current = COPY( tree);
WHILE current != NIL
  previous = current;
  current = nil;
  WHILE previous IS NOT empty
    node = POP(previous);    
    APPEND CHILDREN(node) TO current;  // CHILDREN just pops all elements of node
                                        // APPEND operates on lists, like in Perl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM