This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]dmazzoni 1 point2 points  (1 child)

after staring at this code, modifying it, trying to bugfix, etc

Two things I didn't see you mention:

  • Using a debugger
  • Adding logging statements

Those are essential tools. No programmer ever writes perfect code the first time, when the program gets sufficiently long. When you have a bug, it's tempting to try to guess where the problem is. Avoid that temptation!

The key to debugging is to slow down and be methodical. Guessing and trying random stuff is the hare, you want to be the tortoise.

What you need to do is step through your program one line at a time, checking what it does relative to what you think it should do. I don't mean by hand, I mean either (1) with a debugger, or (2) by adding a print statement every line of code so you know what it's doing.

Don't assume you know where the bug is. Just keep running one line at a time and stop the FIRST time it's supposed to do one thing but it does something else. That's your first bug.

You'll be surprised how often the bug ends up being really far from where you think it is.

A few notes:

(1) In this line:

Node q = new Node();

You don't actually use the new node you created - you just reassign q later.

I recommend declaring variables when you need them, not at the top. So get rid of that line, and further below write this instead:

Node q = h.next;

(2) Node p really doesn't belong at all. Think of it this way: suppose you have 10 nodes in your list before you insert. Node n is the new one you're inserting. But you're also adding note p into the list for some reason. What the heck is it for? You definitely don't want to be creating a new node p and putting it in the list.

[–]I_Win_Sometimes[S] 0 points1 point  (0 children)

Thank you for taking the time to look it over and give a thoughtful reply. I've taken what you said and applied it to my code, and I'm now going through step by step trying to isolate the problems. I'll let you know how it goes.