[英]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'
所以如果我有一个字符“问题”的链表并且位置是 2,那么这个方法应该返回 'e'
Sure.当然。 Just take one step through the list for each
position
:只需对每个
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.您可能需要添加一些
if
语句或try
/ catch
对来处理越界错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.