0

For homework, I am working on writing a LinkedList class, that replaces the LinkedList methods. I'm working on the "set" method.

Here's what I have so far for the set() method. It takes in int index and X item as parameters. The head of the node is in a variable called first. (The whole class is genericized.)

Node<X> p = new Node<X>();
if(index < 0 || index > size()-1){
 throw new Bonfire();
}
int count = 0;
while(count != index){
 p = p.next;
 count++;
}
if(count == index){
 p.item = item;
}

Node class:

public class Node<T>
{
 T item;
 Node<T> next;
}

When I go to run my code against some test code that I have, it fails the test.

Test Code:

LList<String> b = new LList<String>();
b.add("Hello");
b.add("Bye");
b.set(0, "Bonjour");
assertEquals("Bonjour", b.get(0));

Failed test Reason: org.junit.ComparisonFailure: expected:<[Bonjour]> but was:<[Hello]>

(add(), size(), and get() methods are working correctly.)

So my question is, how do I get this to set the element correctly? From this code, and from why it's failing the test, it looks like it's not setting anything at all. If you need any extra information from me, do not hesitate to ask me. Appreciate the help. Thanks!

asked Mar 9, 2019 at 6:13
6
  • Is there a reason why you’re creating a new Node? Don’t you have the head stored in a field? Commented Mar 9, 2019 at 6:16
  • In my other methods I never used a head. Commented Mar 9, 2019 at 6:21
  • Well you appear to just be creating a new Node, which won’t have any links to any other Nodes. Does your class have any fields? Commented Mar 9, 2019 at 6:22
  • I actually forgot I made a first and last variable for the first and last parts of the list, including in the add() method. Commented Mar 9, 2019 at 6:24
  • Yeah, I assumed that was your issue. Commented Mar 9, 2019 at 6:26

1 Answer 1

1

All I needed to do was change Node<X> p to make it Node<X> p = first;.

answered Mar 9, 2019 at 6:25

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.