繁体   English   中英

传递给下面给出的方法的 prev_node 参数的名称应该是什么?

[英]What should be the name of the prev_node argument passed into the method given below?

public class linkedList {
  Node head;

   class Node {
    int data;
    Node next;
    Node(int d){
      data  = d;
    }
  }    
    public void insertAfter(Node prev_node, int new_data){
    if (prev_node == null){
      System.out.print("The given previous node cannot be null");
      return;
    }
    Node new_node = new Node(new_data);
    new_node.next = prev_node.next;
    prev_node.next = new_node;
  }
}

对于给定的链表: 11,73,80,41,22 ,如果我想在 73 之后插入一个数字(例如 0),我可以将其作为insertAfter(llist.head.next,0)传递。

但这是我所能达到的命名prev_node 如果我想在第三个,第四个......等 position 之后输入 0,则作为参数输入。 那么争论会是什么呢?

PS:如果标题具有误导性或混淆性,请原谅我,我无法用正确的词来表达标题。

如果我正确理解您的问题,您想知道当您想在不同位置插入数据时应该为参数传递什么。 仅提供 insertAfter 方法,您需要手动遍历链表。 在您给出的示例中,如下所示:

Insert after 11 -> insertAfter(llist.head, 0)
Insert after 73 -> insertAfter(llist.head.next, 0)
Insert after 80 -> insertAfter(llist.head.next.next, 0)
Insert after 41 -> insertAfter(llist.head.next.next.next, 0)
Insert after 22 -> insertAfter(llist.head.next.next.next.next, 0)

但这不是正确的做法。 您需要提供遍历机制以及其他可以在给定 position 等处添加值的方法。

您需要一个从链表头部开始,遍历到所需的 position 并返回该节点的方法。 然后,您可以将该节点用作您的insertAfter()方法的参数。

public Node getNodeAtPosition(Node head, int position){
    if (head == null || position < 0) 
        throw new IllegalArgumentException("head == null or position < 0");
    Node helper = head;
    while (position != 0) {
        if (helper == null) 
            throw new IllegalArgumentException("position > length of list");
        helper = helper.next;
        position--;
    }
    return helper;
}

暂无
暂无

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

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