Write two functions to find the the number of elements in a linked list: one using a loop, and one using recursion. To represent the linked list use the class lp that I showed you in the lecture.
-
public class lp {
-
public int first;
-
public lp rest;
-
public lp(int first1, lp rest1)
-
{
-
first = first1;
-
rest = rest1;
-
}
-
}
-
The version with the loop looks like the function I showed you in class, which prints all the elements. All you have to do is add a counter, and increment it in the body of the loop. When you reach the end, the counter's value is the length. The recursive version looks like the recursive function for displaying elements of a list. To count the elements, you must rewrite the function so it returns an integer -- the length. In the base case return a zero. In the recursive case, the recursive call returns an integer -- your answer is one more than that integer.
Your program should build a list of length 3 and then call the two length functions to find its length. Building the list is easy:
-
list1 = new lp(1, new lp(2, new lp(3, null)));
-
Your program doesn't need any input. It should look like this to the user:
-
length computed with a loop: 3
-
length computed with recursion: 3
-
thats my assignment and what i have right now is:
-
import java.util.*;
-
import java.io.*;
-
import java.math.*;
-
public class lp{
-
public int first;
-
public lp rest;
-
public lp curr;
-
public int count;
-
public lp(int first1, lp rest1){
-
first = first1;
-
rest = rest1;
-
}//lp construct
-
public static void show(lp first){
-
if(first==null){}//if
-
else{
-
System.out.println(first.rest);
-
show(first.rest);
-
}//else
-
}//show
-
public int loop(lp curr,int counter){
-
lp cur=curr;
-
count=counter;
-
System.out.println("test");
-
while(cur!=null){
-
cur = cur.rest;
-
counter++;
-
}//while
-
System.out.println(counter);
-
return counter;
-
}//lp method
-
public static int listrecurs(int head, lp next){
-
if(next==null){
-
return head;
-
}//if
-
else{
-
return listrecurs(head+1,next);
-
}//else
-
}//recursive method
-
public static void main(String args[]){
-
int beg=1;
-
lp list1 = new lp(1, new lp(2, new lp(3, null)));
-
System.out.println("Length computer with a loop is:");
-
System.out.println(count);
-
System.out.println("Length computer with recursion is:");
-
System.out.println(listrecurs(beg,list1));
-
}//main
-
}//class lp
-
help would be greatly appreciated