I have a linked list that is supposed to return a modified list..
IntNode removeAfterEvery(IntNode head, int oldvalue): If oldvalue is in the list, remove the value immediately after EVERY occurrence of oldvalue. Return the modified list. For example, if the list is currently
9 -> 4 -> 3 -> 12 -> 4 -> 1 -> 4
and we call removeAfterEvery(list, 4), the list should then become
9 -> 4 -> 12 -> 4 -> 4
I have written a code for this and it works.. Only with a problem that it modifies a variable which it is not supposed to and does not modify the one it is supposed to ..
Above is the code which calls the method.. When I try to print "modifiedList" , it prints an empty list whereas it should be the correct one.. and when I try print "head", it prints the correct list. But I never do anything with the original list..
Below is the method..
As you can see above, the method does not change anything in the head list. Whatever it changes, is done in pointer list, which is a copy of head. I am not returning head and not doing anything with head. but still it changes and displays the correct list..
Why is this happening?? I am pretty sure that there is a simple reason behind this but I can't understand what's the mystery.. PLease help!
Your method removeAfterEvery takes the reference of head (of linked list), any modifications to that will reflect in the main method.
Second thing you are returning "pointer" back from your removeAfterEvery method, which is null after your while loop while ( pointer != null) has finished execution. Ideally you should not be returning anything because it is pass by reference. Or use return "head" instead of "pointer" from your removeAfterEvery method which will give you modified list in modifiedList.
I think you are going to have to use the three bits of high technology I keep telling our undergraduates about, to follow the execution of the method and the state of your list. The thre bits of hardware required are
An eraser. Experience shows this to be the most important of the three
Joined: Feb 24, 2010
Campbell Ritchie... You are absolutely right.. I went to my Prof's office hours and he also said that tracing the program helps to debugg it !! He helped me trace the program and pointed the flaws out to me..
Joined: Oct 13, 2005
As I said in your other thread: well done and tell us how you sorted it out.
Joined: Feb 24, 2010
In this program, I was not aware that the line:
pointer = head;
copies the reference..
I thought that the above line actually copies the entire head list into the newly created pointer list.
My prof. told me that a list can not be copied like that.. we need a loop to do so.
The code worked previously also but I never understood why it worked, but now I understand how and why it does.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com