my assignment is to write a 2 functions that check how many elements are in a linked list
one of the functions have to solve it recursively and the other through the use of a loop.
When compiling my code, I run into a load of errors and can't seem to correct them, which I guess is because of my poor knowledge of java syntax.
So.. heres my code:
public class hmwrk2
{
public class lp
{
public int first;
public lp rest;
public lp list1;
public lp(int first1, lp rest1)
{
first = first1;
rest = rest1;
}
}
//15
public static void count_list(lp list1)
{int count = 0;
while (list1 != null)
{count++;}
return count;
}
//22
public static void rCount_list(lp list1)
{
if(list1.first == 0)
{return 0;}
else return rCount_list(list1.rest) + 1;
}
//29
public static void main(String[]args)
{list1 = new lp(1, new lp(2, new lp(3, null)));
int num = count_list(list1);
int num1 = rCount_list(list1);
System.out.println("length computed with a loop: " + num);
System.out.println("length computed with recursion: " + num1);
}
}
The errors from my compiler:
hmwrk2.java:20: cannot return a value from method whose result type is void
return count;
^
hmwrk2.java:26: cannot return a value from method whose result type is void
{return 0;}
^
hmwrk2.java:27: cannot return a value from method whose result type is void
else return rCount_list(list1.rest) + 1;
^
hmwrk2.java:31: cannot find symbol
symbol : variable list1
location: class hmwrk2
{list1 = new lp(1, new lp(2, new lp(3, null)));
^
hmwrk2.java:31: non-static variable this cannot be referenced from a static context
{list1 = new lp(1, new lp(2, new lp(3, null)));
^
hmwrk2.java:31: non-static variable this cannot be referenced from a static context
{list1 = new lp(1, new lp(2, new lp(3, null)));
^
hmwrk2.java:31: non-static variable this cannot be referenced from a static context
{list1 = new lp(1, new lp(2, new lp(3, null)));
^
hmwrk2.java:32: cannot find symbol
symbol : variable list1
location: class hmwrk2
int num = count_list(list1);
^
hmwrk2.java:33: cannot find symbol
symbol : variable list1
location: class hmwrk2
int num1 = rCount_list(list1);
^
9 errors
I have been playing around with the syntax for an hr and am a bit stuck