This should be a fairly basic question, but I cannot for the life of me figure it out. I’m using two files given to me by my instructor, and I have to write a method removeFirst that will remove the head from a declared linked list and return that old head value. It cannot take any parameters. Here’s file 1 and file 2.
My code for removeFirst and debugging is below. I do not know how to reference the aList without being able to use it as a parameter, especially since the linked list is not global. When I use the debugging code, it prints aList, then prints 21 (the head of the list that it should be removing, and which is what removeFirst should be returning), but then it does not print the updated linked list — it’s just blank.
removeFirst code:
public IntNode removeFirst() {
IntNode cur = getHead();
head = cur.getNext();
head.setPrev(null);
cur.setNext(null);
return cur;
}
Debug code (at bottom of main):
for(int i = 0; i < aList.size(aList.getHead()); i++) {
aList.print(aList.findObject(i));
}
aList.print(aList.removeFirst());
System.out.println("");
for(int j = 0; j < aList.size(aList.getHead()); j++) {
aList.print(aList.findObject(j));
}
You need to
return head;instead ofreturn cur;EDIT Sorry. I evidently misunderstood your problem statement. The above is appropriate if the
removeFirst()method is supposed to return the new head of the list. If it’s supposed to return the removed element (as is clear now after your comment and edit of the original post), then it should be working properly.Presumably
removeHead()is an instance method in your list class. You don’t need to pass a parameter because the list is available asthisinside the method.It would help to see the class definition for
aList. Yourfile 1link says it’s to MyLinkedList.java, but the pasted code there is for IntNode.java.EDIT 2 The problem, I think, may be your debug code.
findObject(j)does not return thejth element of the list–it returns the list element that containsjas a value. From the code, it looks likeMyLinkedList.print(IntNode)prints the entire list starting at the indicated node. What happens if you replace theforloops in your debug code with simply: