Following is my code to find middle node of double linked list but it works only for odd number of nodes. i cannot figure out how to take care of case of even number of nodes:
public Object findMiddleNode() {
DLNode first = getHeadNode();
DLNode last = getTailNode();
while(first!=last) {
first = first.getNext();
last = last.getPrevious();
}
return first.getElement();
}
this is my updated code:
public MyDequeue findMiddleNode() {
DLNode first = getHeadNode();
DLNode last = getTailNode();
MyDequeue m = new MyDequeue();
while(first!=last && first.getNext()!= last) {
first = first.getNext();
last = last.getPrevious();
}
if(first == last) {
m.insertLast(first.getElement());
return m;
}
else {
m.insertLast(first.getElement());
m.insertLast(last.getElement());
return m;
}
}
the class MyDequeue is my implementation of a doubly linked list. the reason I returned MyDequeue is because I already had a static print method that prints the elements of a doubly linked list.
For an even number of nodes, first and last pass each other at the middle. For example, if you have 4 nodes 1..4, first will be 2 when last is 3. At the next iteration, first will be 3, and last will be 2. So you never fail the while loop test (first != last) needed to exit the loop at the proper point. A simple fix is to modify your while test to be
while ((first != last) && (first.getNext() != last)) {.