简体   繁体   中英

How can I find the node given a position of a linkedlist?

public class Practice{
    private Node head;
    private int count = 0;

    public class Node{
        private char data;
        private Node next;

        private Node(char data) {
            this.data = data;
            next = null; 
        }
    }

  public Practice() {
    head = null;
  }
 public Character getData(int position) {

 }
}

is there a way to find the node within a linkedlist if I have a parameter position? so if I have a linkedlist of characters "question" and position is 2, then this method should return 'e'

Sure. Just take one step through the list for each position :

public Character getData(int position) {
  Node current = head;
  while(position > 0) {
    current = current.next;
    position--;
  }
  return current.data;
}

You may need to add some if statements or try / catch pairs to deal with out-of-bounds errors.

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