I wanted to learn about linked list, so I tried to implement one from scratch. The logic makes sense, however when adding a value to the linkedlist it overwrites the values. So if I added the ones 1 -> 2 -> 3 -> 4 -> 5, but I wont get these values when I print the content of my linked list...
Any idea how to fix the solution?
public class LinkedListM {
Node head;
class Node {
Node next;
int value;
Node(int value) {
this.value = value;
this.next = null;
}
}
public void add(int value) {
// System.out.println("inserting: " + value);
Node node = new Node(value);
if (head == null) {
head = node;
}
else {
while (head.next != null) {
// System.out.println(head.value + " -> " + head.next.value);
head = head.next;
}
head.next = node;
}
}
public void remove(int value) {
LinkedListM list = new LinkedListM();
Node dummy = new Node(0);
dummy.next = head;
while (dummy.next != null) {
if (dummy.next.value == value) {
if (dummy.next.next == null) {
dummy.next = null;
}
else {
dummy.next = dummy.next.next;
}
}
dummy = dummy.next;
}
}
}
Here is me testing the linked list:
public class p {
public static void main(String[] args) {
LinkedListM ll = new LinkedListM();
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);
ll.add(5);
// System.out.println(ll);
while(ll.head.next != null) {
System.out.print(ll.head.value + " -> ");
ll.head = ll.head.next;
}
System.out.println();
}
}