[英]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.