Reputation: 159
I am trying to search for a node based on the position of the node in a doubly linked list. For example, if the list contains 1,2,3,4,5 and I want to get position 3, it will return positions data, which is 3. I was able to get the first and second position, but when I try any other position after the second, it only returns the second position. I am not sure what is wrong. Here is my code so far:
Insert Method
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++;
}
Search Method
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;
}
Test:
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);
output:
1: 1
2: 2
3: 3
4: 4
5: 5
Node: 2
Upvotes: 0
Views: 2474
Reputation: 3019
Tweak the for loop a bit:
Break loop when position is reached.
for(int i = 2; i <= size; i++)
{
found = head.next;
if(i == pos)
{
break;
}
}
Upvotes: 3
Reputation: 376
The problem is at this line:
found = head.next;
You always return the second element (and the first one works thanks to the first branch of your if
statement).
You should instead run through the list and get the correct element.
Upvotes: 3