Thursday, September 27, 2012

Homework 4


Write a function called "odd" that takes a linked list and returns the odd-numbered elements. Actually, write two functions called "odd" and "even". odd(L) returns a list of the 1st,3rd,5th... items in L. even(L) returns a list of the 2nd,4th,6th... items in L. And each function calls the other. These two functions are based on a simple observation. L.next is like L, but with the first item missing. If we take away the first item, item N+1 becomes item N. So the 2nd,3rd,4th elements of L are the 1st,2nd,3rd elements of L.next. Now if N+1 is odd, N is even, while if N+1 is even N is odd. So the odd members of L.next are even members of L, and the even members of L.next are odd members of L. Then we can compute odd(L) as follows. If L is null return null. Otherwise return a list whose first item is L.item, while its tail is even(L.next). To compute even(L): If L is null return null. Otherwise return odd(L.next). Your main function should read a list of positive integers from the command line, with -1 terminating the list. It should form a linked list containing these integers, compute the list of odd members, and print them.

Possible Solution:

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

 1/ list.java

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

2/ homework4.java

import java.util.Scanner;

public class homework4
{

   public static void main(String[] args)
  {
       int n = 0;
       list l = null, new_list = null;

      // Create a scanner to read from keyboard
      Scanner scanner = new Scanner (System.in);
 
      while (n != -1)
     {  
          System.out.println("enter a number: ");
         n = scanner.nextInt();
         if (n!= -1)
          l = insert(n, l);
     }
      new_list = odd(l);

     show_list(new_list);
     System.out.println();
 
    }

  static list odd(list y)
 {
   if (y == null)
     return null;
   else
     return new list(y.first, even(y.rest));
 }

 static list even(list y)
 {
   if (y == null)
     return null;
   else
     return odd(y.rest);
 }

 static list insert(int x, list y)
 {
   list current = y;
  
   if (y == null)
     return new list(x, y);
   else
   {
     while (current.rest != null)
       current = current.rest;
     current.rest = new list(x, null);
     return y;
   }
 }

 static void show_list(list y)
 {
  if(y != null)
  {
   System.out.print(y.first + " ");
   show_list(y.rest);
  }
 } 

}