简体   繁体   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;
  }
}

For a given linked list: 11,73,80,41,22 , if I'd want to insert a number (eg. 0) after 73, I can pass it as insertAfter(llist.head.next,0) .对于给定的链表: 11,73,80,41,22 ,如果我想在 73 之后插入一个数字(例如 0),我可以将其作为insertAfter(llist.head.next,0)传递。

But that is as far as I can reach to name a prev_node .但这是我所能达到的命名prev_node What goes in as argument if I wanted to enter the 0 after the third,fourth...etc position.如果我想在第三个,第四个......等 position 之后输入 0,则作为参数输入。 What will the argument be then?那么争论会是什么呢?

PS: Forgive me if the title is misleading or confusing, I wasn't able to put the query in right words for the title. PS:如果标题具有误导性或混淆性,请原谅我,我无法用正确的词来表达标题。

If I understand your question right, you want to know what should be passed for the argument when you want to insert data at different positions.如果我正确理解您的问题,您想知道当您想在不同位置插入数据时应该为参数传递什么。 With only insertAfter method provided you need to traverse through the linked list manually.仅提供 insertAfter 方法,您需要手动遍历链表。 In the example given by you it goes as below:在您给出的示例中,如下所示:

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)

But this is not a correct approach.但这不是正确的做法。 You need to provide traversal mechanisms as well as other methods which can add the value at the head, at the end of the list, at a given position etc.您需要提供遍历机制以及其他可以在给定 position 等处添加值的方法。

You need a method that starts from the head of the linked list, traverses to the desired position, and returns that Node.您需要一个从链表头部开始,遍历到所需的 position 并返回该节点的方法。 You can then use that Node as an argument to your insertAfter() method.然后,您可以将该节点用作您的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