0
\$\begingroup\$

There is a solution floating around about using 2 pointers. But I decide to keep the implementation much simpler by using basic constructs that works use to build basic methods of a singly list list data structure.

The code works. My question is, am I off the hook from making it better as long as the code works? Is the code sufficient?

 public Object findMiddleElement()
 {
 Node node = head;
 if(size % 2 != 0)
 {
 for(int i = 0; i < size/2 ;i++ )
 {
 node = node.getNext();
 }
 }
 else
 {
 System.out.println("there is no middle element");
 node.setElement(null);;
 }
 return node.getElement();
 }
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 13, 2015 at 0:47
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It could be a little easier to read like this:

public Object findMiddleElement() {
 Node node = head;
 if(hasMiddleElement()) {
 for(int i = 0; i < size / 2; i++) {
 node = node.getNext();
 }
 } else {
 System.out.println("there is no middle element");
 node.setElement(null);
 }
 return node.getElement();
}
private boolean hasMiddleElement() {
 return size % 2 == 1;
}

This works if size is set in the class.

answered Jul 13, 2015 at 1:58
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.