Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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();
        }
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.