Hello,
For some reason, my program prints out extra zero from my linked list
Can anyone tell me why?
Thank you
public class Main {
public static void main(String[] args) {
IntNode my = new IntNode(5,null);
LinkedList list = new LinkedList();
list.createList(0);
list.addValue(1);
list.addValue(23);
list.addValue(3);
list.addValue(4);
list.print();
list.getLength();
}
}
public class LinkedList {
private IntNode head;
private IntNode next;
private IntNode prev;
public LinkedList() {
head = null;
} // Create(int value) – this method should create an integer singly list and return the head.
public IntNode createList(int n) {
while(head== null){
head = new IntNode(n, head);
}
head.addNodeAfter(n);
return head;
}
// Add(int value) – this function should add a value in sorted order (low to high) to the list
public void addValue(int value) {
IntNode cur = head;
head.addNodeAfter(value);
if (value <= cur.data){
head=cur.link;
}
else{
head=cur;
}
}
// Remove(int value) to remove all the nodes with the value
public boolean removeAll(int target) {
IntNode cur;
IntNode targetNode;
targetNode = IntNode.listSearch(head, target);
if (targetNode == null){
return false;
}
else {
// I am not sure what to do next (ask Prof)
head = targetNode.link;
}
System.out.println(" The List is empty, there is nothing to remove");
return true;
}
// GetLength() to get the length
public void getLength() {
int count=0;
IntNode cur= null;
// while (cur.link != null);
for (cur = head; cur != null; cur = cur.link) {
count++;
}
System.out.println("Test for count:"+ count);
}
// Reverse () to reverse the list
public void reverse() {
IntNode prev = null;
IntNode cur = head;
while (cur != null)
{
cur = head.link;
head.link = prev;
prev = head;
head = cur;
}
head = prev;
}
// to print the list.
public void print() {
IntNode cur = head;
while (cur != null) {
System.out.println("Printed Node is: " + cur.data);
cur = cur.link;
}
}
}
public class IntNode {
public int data;
public IntNode link;
public IntNode(int initialdata, IntNode initiallink) {
data = initialdata;
link = initiallink;
}
public void addNodeAfter(int item) {
link = new IntNode(item, link);
}
public IntNode removeNode() {
if (link != null) {
link = link.link;
}
return null;
}
public static IntNode listSearch(IntNode head, int target) {
IntNode cur;
while (head != null) {
for (cur = head; cur != null; cur = cur.link) {
if (target == cur.data) {
return cur;
}
}
}
return null;
}
}