簡體   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