簡體   English   中英

如何找到給定鏈表位置的節點?

[英]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) {

 }
}

如果我有參數位置,有沒有辦法在鏈表中找到節點? 所以如果我有一個字符“問題”的鏈表並且位置是 2,那么這個方法應該返回 'e'

當然。 只需對每個position的列表進行一步:

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

您可能需要添加一些if語句或try / catch對來處理越界錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM