简体   繁体   中英

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) .

But that is as far as I can reach to name a prev_node . What goes in as argument if I wanted to enter the 0 after the third,fourth...etc position. 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.

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. 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.

You need a method that starts from the head of the linked list, traverses to the desired position, and returns that Node. You can then use that Node as an argument to your insertAfter() method.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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