Monday, October 8, 2012

Homework 5

Write a recursive method called "occur" that takes two arguments: a linked list of integers L and an integer N. It should return the Boolean true if N occurs in the list L, otherwise false. If L is null the answer must be false. If not, compare N to L.item. If they are equal, the answer is yes. If not, find the answer by calling the same function on the tail of L. Your main method should create a list L with members 1,2,3,4,5 and call the "occur" method twice: once to check if 4 occurs in the list L, and once to check if 9 occurs. Print both results. 
Possible Solution:

Compile two files in the same folder:
                             javac list.java
                            javac homework5.java
Then run:    java homework5

 1/ list.java


class list
{
     public int first;
     public list rest;
   
     public list(int x, list y)
    {
        first = x;
        rest = y;
    }
}

2/ homework5.java

public class homework5
{

 public static void main(String[] args)
 {

   boolean ans;
   int N;
   list L = new list(1, new list(2, new list(3, new list(4, new list(5, null)))));
 
  N = 4;
  ans = occur(L, N);
  if (ans == true)
    System.out.println(N + " is in the list");
  else
    System.out.println(N + " is not in the list");
 
  N = 9;
  ans = occur(L, N);
  if (ans == true)
    System.out.println(N + " is in the list");
  else
    System.out.println(N + " is not in the list");
 
 }

 static boolean occur(list L, int N)
 {
  if (L == null)
    return false;
  else
  {
    if (L.first == N)
      return true;
    else
      return occur(L.rest, N);
  }
 }
 

}