I am practicing my algorithms and i am attempting a problem to delete even values in a linked list but it fails. When attempting to print the linked list class after deleting the even values as i provided test cases to see if the program works correctly. It prints out 10, and 1. 11 and 1 should be the values printed instead.
public class LinkedList
{
private Node head;
public LinkedList() {
this.head = null;
}
public void add(int data) {
Node node = new Node(data);
if(head == null) {
node.setNextNode(head);
head = node;
}
else {
Node curr = head;
while(curr.next != null) {
curr = curr.getNextNode();
}
curr.setNextNode(node);
}
}
public void removeEven() {
if (this.head==null) return;
Node prev=null, curr = head;
while(curr != null) {
if(curr.data%2 == 0) {
if(prev == null) {
Node node = curr.getNextNode();
node.setNextNode(prev);
prev = node;
curr = curr.getNextNode().getNextNode();
}
else {
Node node = curr.getNextNode();
prev.setNextNode(node);
curr = curr.getNextNode();
}
// curr = curr.getNextNode();
}
else{
prev = curr;
curr = curr.getNextNode();
}
}
}
public void print() {
if(head == null) return;
Node curr = head;
while(curr != null) {
System.out.println(curr);
curr = curr.getNextNode();
}
}
public static void main(String[] args)
{
LinkedList h = new LinkedList();
h.add(10);
h.add(1);
h.add(11);
h.add(8);
h.removeEven();
h.print();
}
}
class Node {
int data;
Node next;
public Node(int data) {
this(data, null);
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node getNextNode() {
return this.next;
}
@Override
public String toString() {
return "Data: "+this.data;
}
}