I am trying to write a program that takes an integer and inserts it into the second position in the linked list, but when I run my program it prints out (127, ) when I want it to print out (12, 7). I know it is probably an easy fix, but I am unsure of how to fix this small error. I have tried switching words around like head and tail and next, but nothing I do seems to work. Any input would help a ton!
public class IntSinglyLinkedList {
private static class Node {
private Integer element;
private Node next;
public Node(Integer e, Node n) {
element = e;
next = n;
}
private Node head = null;
private Node tail = null;
private int size = 0;
public IntSinglyLinkedList() { }
public int size() { return size; }
public void addSecond(Integer e) {
if(head == null)
return;
Node Final = new Node(e, head);
Final.next = head.next;
head.next = Final;
}
public static void main(String[] args) {
IntSinglyLinkedList sl = new IntSinglyLinkedList();
sl.addFirst(12);
sl.addSecond(7);
System.out.println(sl.toString());
}
}
My toString also looks like this if this is any help!
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node walk = head;
while (walk != null) {
sb.append(walk.getElement());
if (walk != tail)
sb.append(", ");
walk = walk.getNext();
}
sb.append(")");
return sb.toString();
}
my addFirst method
public void addFirst(Integer e) {
head = new Node(e, head);
if (size == 0)
tail = head;
size ;
}
CodePudding user response:
Why aren't you just using a LinkedList?
LinkedList<Integer> ll = new LinkedList<>();
ll.add(12);
ll.add(1, 7);
System.out.println("LinkedList is: " ll.toString());
Output would be: LinkedList is: [12, 7]
CodePudding user response:
You never update your tail element after your addFirst
, so the ,
will not be printed after the first element.
You have to add tail = Final;
in your addSecond method to make this particular example to print correctly.
That answers the specific question of why you get (127,)
printed instead of (12, 7)
in this particular case.
However, it is hard to see where you are going with this. Are you planning to write a new method for every element you want to add?
CodePudding user response:
You don't have to rely on the equality of references. Change this condition walk != tail
to this walk.equals(tail)
. With this change alone the code will print (12, 7)
.
The way of adding new elements to the list seems strange. I'm talking about the method addSecond()
it looks very contrived. And none of your methods doesn't track the reference to the tail properly. Once assigned in the addFirst()
it sticks with the same value.
By the way, Final
isn't a good name, it's not very meaningful and violates the convention.
To resolve the issue with the tail
reference you have to check wherether tail
is pointing to the head
inside the addSecond()
. And only if it is the case then assign the newly created Node to be a tail
.