我试图根据节点在双向链表中的位置来搜索节点。例如,如果列表包含 1,2,3,4,5 并且我想获取位置 3,它将返回位置数据,即 3。我能够获取第一个和第二个位置,但是当我尝试任何第二个之后的其他位置,它只返回第二个位置。我不确定出了什么问题。这是到目前为止我的代码:
插入方法
public void insertAtStart(String data)
{
Node ptr = new Node(data);
if(head == null)
{
head = ptr;
tail = head;
}
else
{
head.prev = ptr;
ptr.next = head;
head = ptr;
}
size++;
}
搜索方式
public Node searchAt(int pos)
{
Node found = head;
if(isEmpty())
{
System.out.println("List is empty");
return null;
}
if(pos == 1)
return found;
for(int i = 2; i <= size; i++)
{
if(i == pos)
{
found = head.next;
}
}
return found;
}
测试:
doc.insertAtStart("1");
doc.insertAtStart("2");
doc.insertAtStart("3");
doc.insertAtStart("4");
doc.insertAtStart("5");
doc.printReverse();
Node newNode = doc.searchAt(4);
System.out.println("Node" + newNode.data);
输出:
1: 1
2: 2
3: 3
4: 4
5: 5
Node: 2
最佳答案
问题出在这一行:
found = head.next;
您始终返回第二个元素(第一个元素可以通过 if
语句的第一个分支起作用)。
您应该遍历列表并获取正确的元素。
关于java - 在双向链表的给定位置搜索节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42322931/