Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, November 26, 2007

MaximallyBalanced or Complete Binary Tree

// Queue version -- only version totally working so far!
    public boolean isMaximallyBalanced (TreeNode x){ 

            boolean scanningNulls = false;

            Deque q = new LinkedList ();
            q.addFirst(x);

            while (q.size() != 0) {
                TreeNode n = q.remove();

                if (scanningNulls) {
                    if (n != null) 
                        return false;
                }
                else {
                    if (n == null) {
                        scanningNulls = true;
                    }
                    else {
                        q.add(n.myLeft);
                        q.add(n.myRight);
                        
                    }
                    }
                }
            
            return true;
        }

// Adopted from: www.boyet.com/Articles/CheckingForHeap.html 

Saturday, November 17, 2007

Doubling a Linked List

//couldn't find a better way to do this...

public void double2 ( ) {
  /* Invariant is L with 2 first ones and rest*/
  ListNode q, w;
  w = q = new ListNode (null);
  
  for (ListNode p = myHead; p != null; p = p.myRest) {
       
       q.myRest = new ListNode(p.myFirst, p);
       q = q.myRest.myRest;
       
               
     }
  myHead = w.myRest;
   /*ListNode p = myHead;
  ListNode p1 = myHead.myRest;
  ListNode p2 = myHead.myRest.myRest;
  
  myHead = new ListNode (p.myFirst, p);
  myHead.myRest.myRest = new ListNode (p1.myFirst, p1);
  myHead.myRest.myRest.myRest.myRest = new ListNode (p2.myFirst, p2);
   */
 }
 
 public void double3 ( ) {
  ListNode w;
  w = new ListNode (myHead.myFirst);
  for (ListNode p = myHead; p != null; p = p.myRest) {
   w.myRest= new ListNode(p.myFirst, p);
   w = w.myRest.myRest;
   System.out.println(this.toString());
  }
  myHead = new ListNode (myHead.myFirst, myHead);
 }


Friday, November 9, 2007

Access Modifiers: public, private, proctecd, package protected(default)

Public : declarations represent specifications – what clients of a package are supposed to rely on. Package Private (default): declarations are part of the implementation of a class that must be known to other classes that assist in the implementation. Protected: declarations are part of the implementation that subtypes may need, but that clients of the subtypes generally won’t. Private: declarations are part of the implementation of a class that only that class needs. *********************************************************************** Import: Does not grant any special access; it only allows abbreviation.

Thursday, November 8, 2007

End of HFJ

Announcing the end of going through HFJ. Admittedly, only a first pass... But finally finished back back to back...well maybe except for code kitchens on the beat program and some of the appendices...But did finish all the chapters, didn't I? It's a great book and one that really make stuff look easy. As they say, the best always make it look easy! And this is kind of, one of the best example of that saying! Took me 5 weeks to go through it all. But it was a great experience. I'll miss, reading that book, it seems to me! In any case, on to more stuff then....

Wednesday, November 7, 2007

Format Specifiers

Format Specifiers:

% [argument number] [flags] [width] [.precision] type

%: says, ‘insert arument here’ and format it using these instructions.

flags: these are for special formatting options like inserting commas, or
Putting negative numbers in parentheses, or to make the numbers
Left justified

width: This defines the Minimum number of characters that will be sued.
That’s minimum not TOTAL. If the number is longer than the width,it’ll still be used in
full, but if it’s less than the width, it’ll be padded with zeroes. Most of the time
this does not need to be specified.


.precision:  It defines the precision. In other words, it sets the number of decimal places.

type: Type is mandatory and will usually be ‘d’ for a decimal integer or ‘f’ for a floating
point number.

E.g. :
format(“%,3.1f”, 91.0000000); -> 91.0

complete example code:

public class FormatTest {

static String x = "";
static double y = 91.000000;

public static void main(String[] args) {

 x = String.format("%,3.1f", y);
 System.out.println(x);

}

} // produces: 42.0

// Adopted from HFJ

Tuesday, November 6, 2007

Collection class tidbits...

I had to say I do > in a picture...

Generic class definitions and one implementation

Generic class definitions and one implementation

Type parameterization goes in the horizontal direction while abstraction takes care of the 
vertical direction. The idea is the same, reusability and other OOP goodness. 

“The Class, the central notion in Object Technology, can be viewed as the product of the 
corporate merger between the module and type concepts.”

A generic class declared as C[G] is, rather than a type, a type pattern covering an infinite 
set of possible types; you can obtain any one of these by providing an actual generic 
parameter – itself a type - corresponding to G.

Java allows the use of wildcards to specify bounds on what type of parameters a given
 generic object may have. E.g. List indicates a list which has an unknown object 
type.  
List  is pronounced as List of Unknowns.

Void printCollection (Collection  c) {
 For (Object e : c)
     System.out.println(e);
} // will work for any collection of objects. 
   //But if the formal argument is Collection   then, it will not!

This is because, in general, if Parrot is a subtype (subclasss or subinterface) of 
Bar, and G is some Generic type declaration, it is not the case that G is a
subtype of G.

To specify the upper bound of a generic element, the extends keyword is used, which
 indicates that the generic type is a subclass (either extends the class, or 
implements the interface) of the bounding class.

So List means that the given list contains objects which extend the 
Shape class; for example, the list could be List or List.

To specify the lower bound of a generic element, the super keyword is used, which 
indicates that the generic type is a superclass of the bounding class.

So, List could be List or List or List.

Example Implementation: The  fictitious “formal generic parameter” here is E.

public class OopList {
 
 protected class Node{
  E element;
  Node next;
  Node (E e, Node n){ element = e; next = n; }
 }
 
 protected Node _head;
 
 
 /** Construct the empty List. */
 public OopList() { _head = null; }
 
 /** Add item to the beginning of the List. */
 
 public void add (E element) {
  _head = new Node (element, _head);
 }
 
 /** Return true iff this List is empty. */
 
 public boolean isEmpty() { return _head == null; }
 
 public String toString() {
  String x = "( ";
  while (!isEmpty()){
   x = x + this._head.element + " ";
   _head = _head.next;
  }
  return x + ")";
 }
 
 /** Allow iteration. */
 
 public java.util.Iterator elements() {
  return new OopListIterator (this);
 }
 
 public static void main (String [] args) {
  OopList OopLT = new OopList ();
  OopLT.add("Hello");
  OopLT.add("Not");
  OopLT.add("Done");
  
  System.out.println(OopLT.toString());
  
 }
} // End of class 



//********************************************************


// beginning of Iterator class. OopListIterator.

import java.util.*;

public class OopListIterator implements Iterator {
 
 private OopList _list;
 private OopList.Node _current;
 
 public OopListIterator (OopList list){
  _list = list;
  _current = _list._head;
 }
 
 public boolean hasNext () { return (_current != null); }
 
 public E next() throws NoSuchElementException {
  if (_current == null)
   throw new NoSuchElementException();
  E result = _current.element;
  _current = _current.next;
  return (result);
 }
 
 public void remove() throws UnsupportedOperationException {
  throw new UnsupportedOperationException();
 } 
  
 
}

//************************************************ Test Classes


public class Animal {

 protected String x;
 protected int age;
 protected boolean pet;
 
 public Animal (String y, int v, boolean i){
  x = y;
  age = v;
  pet = i;
 }
 
 public String toString (){
  String voila = "";
  voila = "Name: " + x + "  " +  "Age: " + age + " "+ " Pet: " + pet;
  return voila;
 }
 
 
 
 public static void main (String [] args){

  Animal me = new Animal ("Tiger", 33, true);
  System.out.println("Tiger is: ");
  System.out.println(me.toString());
 
  Animal Parrot1 = new Parrot ("P", 3, true);
  System.out.println("Parrot is: ");
  System.out.println(Parrot1.toString());
 }
}

//*****************************************

public class Parrot extends Animal {
  
  public Parrot (String x, int v, boolean z){
   super(x, v, z);
   this.x = "Parrot";
  }
  
 }


// JUNIT Testing:
//********************************************************

import junit.framework.TestCase;


public class OopListTest extends TestCase {

 public void OopListConstructorTest() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
  
 }
 
 public void testOopList() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
 }

 public void testAdd() {
  OopList OopLT = new OopList ();
  OopLT.add("Hello");
  OopLT.add("Not");
  OopLT.add("Done");
  assertEquals ("( Done Not Hello )", OopLT.toString());
  
 }

 public void testIsEmpty() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
 }

 public void testElements() {
  OopList OopLT = new OopList ();
  OopListIterator iter1 = new OopListIterator (OopLT);
  assertFalse (iter1.hasNext());
  OopLT.add("Hello");
  OopLT.add("Not");
  OopLT.add("Done");
  OopListIterator iter = new OopListIterator (OopLT);
  
  assertFalse (OopLT.isEmpty());
  assertTrue (iter.hasNext());
  assertTrue (iter.hasNext());
  assertEquals("Done", iter.next().toString());
  assertEquals("Not", iter.next().toString());
  assertEquals("Hello", iter.next().toString());
  assertFalse (iter.hasNext());
 
 }
 
 /* Now let's try with another set of Objects 
  * Actual Generic Parameters in this case are Animal objects.
  * Type erasure and Generically derived type is Animal here.
  * */
 
 
 public void testElements3() {
  OopList OopLT = new OopList ();
  assertTrue (OopLT.isEmpty());
  OopListIterator iter1 = new OopListIterator (OopLT);
  assertFalse (iter1.hasNext());
  
  Animal me = new Animal("Tiger", 33, true);
  
  Animal horse = new Animal("Horse", 10, true);
  
  Animal Parrot1 = new Parrot ("P", 3, true);
  OopLT.add(Parrot1);
  OopLT.add(horse);
  OopLT.add(me);
  OopListIterator iter = new OopListIterator (OopLT);
  assertFalse (OopLT.isEmpty());
  assertTrue (iter.hasNext());
  assertTrue (iter.hasNext());
  assertEquals("Name: Tiger  Age: 33  Pet: true", iter.next().toString());
  assertEquals("Name: Horse  Age: 10  Pet: true", iter.next().toString());
  assertEquals("Name: Parrot  Age: 3  Pet: true", iter.next().toString());
  assertFalse (iter.hasNext());
  OopListIterator iter2 = new OopListIterator (OopLT);
  assertTrue (iter2.hasNext());
  assertTrue (iter2.hasNext());
  assertEquals("Name: Tiger  Age: 33  Pet: true", iter2.next().toString());
  assertEquals("Name: Horse  Age: 10  Pet: true", iter2.next().toString());
  assertEquals("Name: Parrot  Age: 3  Pet: true", iter2.next().toString());
}
}

// Adopted from: http://www.cs.huji.ac.il/course/2005/oop/lecture-slides.html


Thursday, November 1, 2007

doubling a List

//couldn't find a better way to do this...

public void double2 ( ) {
  /* Invariant is L with 2 first ones and rest*/
  ListNode q, w;
  w = q = new ListNode (null);
  
  for (ListNode p = myHead; p != null; p = p.myRest) {
       
       q.myRest = new ListNode(p.myFirst, p);
       q = q.myRest.myRest;
       
               
     }
  myHead = w.myRest;
   /*ListNode p = myHead;
  ListNode p1 = myHead.myRest;
  ListNode p2 = myHead.myRest.myRest;
  
  myHead = new ListNode (p.myFirst, p);
  myHead.myRest.myRest = new ListNode (p1.myFirst, p1);
  myHead.myRest.myRest.myRest.myRest = new ListNode (p2.myFirst, p2);
   */
 }
 
 public void double3 ( ) {
  ListNode w;
  w = new ListNode (myHead.myFirst);
  for (ListNode p = myHead; p != null; p = p.myRest) {
   w.myRest= new ListNode(p.myFirst, p);
   w = w.myRest.myRest;
   System.out.println(this.toString());
  }
  myHead = new ListNode (myHead.myFirst, myHead);
 }


Don't Forget Your Scheme!


Well, wasted half a day yesterday by forgetting my Scheme. Finally,
A&S came to the rescue, somehow remembered after wasting a lot of time,
that 'append!' was one of the examples in that book and the same stuff
basically can be done in Java too..

Here is the Scheme version:


 (define (append! x y)
   (set-cdr! (last-pair x) y)
 x)
Here last-pair is a procedure that returns the last pair in its argument:

 (define (last-pair x)
   (if (null? (cdr x))
       x
   (last-pair (cdr x))))

From there the Java version for append! or what we call, descructively
appending a list to another one while not instantiating another one is easy.
Though we have to instantiate a new ListNode...

         ListNode LastP = lastPair(list1);
  LastP.setNext(list2);   //setNext is set-cdr!
  return list1;

Here's the helper for Java...

      public static LNode lastPair(ListNode y){
 if (y.next().isEmpty()){
    return y;
 } else 
  return lastPair(y.next());
      }


Another instersting one is the Reverse method: 

Scheme Version:

       (define (reverse L)
 (reverse-helper L '( )) )
 
       (define (reverse-helper L so-far)
      (if (null? L) so-far
   (reverse-helper (cdr L) (cons (car L) so-far)) ) )

Java version works the sameway if we are writing the recursive one:

return reverseHelper (list1.next() ,  new LNode (list1.data(), sofar) );


Wednesday, October 31, 2007

Deconstructing a Scheme recursive function and implementing it as a java method..


Deconstructing a Scheme recursive function and implementing it as a java method..
 
In scheme, to add an element to the end of the list we have the following procedure:

 (define (add-to-end-of-list list a)
     (if (null? list) '(a)
       (cons (car list) (add-to-end-of-list (cdr list) a)) ) )

This is recursive. And answer returns after it hits base case and everybody is happy!

Ecept for the stack I guess.

 
Amazing thing is, we can pretty much do the same in Java!
 
 public Lnodeadd (Object a) {

        return LnodeAddHelper (this, a);

 }

 private static LnodeAddHelper (Lnode L, Object a) {

        if (L.Empty()) {

                return new Lnode (a);

        } else {

                return new Lnode(L.first(), LnodeAddHelper (L.rest(), a)); 
                //the above line is mind blowing or what???

        }

 }

Here Lnode is the singly linked List. first() is car, rest() is cdr and the Lnode constructor is the cons.

Sunday, October 28, 2007

Iterator for Collection and Nested Class

When we are creating an Iterator for a class, we are actually calling on the nested/inner class maybe. If the iterator is inside the main class, it makes perfect sense to put the iterator there with its hasNext(), hasElement(), initIterator(), and other methods... So we create an iterator like this and looks like a method call but it's a call on the nested class...

          Iterator iter = mySomeKindOfList.myListIterator ( );

Tuesday, October 23, 2007

Inheritence and PolyMorphIsm


Don't believe in any 'ISM' but making an exception here, perhaps the SUN guys will
change the word some time later as all 'ISM' brings bad news in the end. Maybe,
PolyMorphISM is no exception to this 'invariant'!

For the following discussion, we have to classes, Super and Sub which extends the 
Super class, both class defines the same non-static method (same signature, return 
type) within itself, we call this method methodx

Super A = new Sub ();
A.methodx();

Calls the methodx of the Sub class, _not_ the Super class.
This is dynamic binding at work. Most important thing to remember is that Dynamic 
Type is the KING!
Doesn’t matter what the static Type is! The method to call at run time WILL BE 
based on the dynamic type.
Thus in the above, when we do the method call, the ‘methodx’ of the Sub class will 
be called even though static type is Super. But we don’t care about static type with 
dynamic binding.

Sub B = new Super ();

This results in compile time error, since we can not go from low to high in terms of 
assignment. The way I put it is that the servant can not wear the Master’s shoes! 
(At least according to Java Compiler). If the Super class is the Master and the Sub
class is the slave, then Sub class can not own property titles of the Master. Here 
we extend the analogy this way....the Super class is the Master and objects of that
class are the property of the Master. The static type of the Parent class is 
actually the title deeds on the property. So, here we are thinking that, in terms of
references, or arrows, those are actually property titles and the actual property is 
the actual instantiated objects, while the Master is actually the Class itself. Ok…
maybe convoluted. But stay with me, I’m making this up as we go along! :) In any 
case, in terms of the analogy, Static type Sub is the slave and all variables of its 
type (like B) can only be of deeds to its own property (meager though they maybe or 
not…after all can slaves really own ANYTHING? They can not, only they seem to do so
some times, which is an illusion. This hypothesis will be verified and testified by
Java compiler in a little while as we will see!), i.e. instantiated objects of its 
own type (Sub class type). If it tries otherwise, Java will stop it. Thus we will 
get a compile error.

Super C = new Super ();
((Sub) C).methodx();

This results in a run time error. Here we have the Master and all, but we try to 
cast the master as a slave. This passes through compiler, as they are all beings of
the same world. However, when running it will found that the dynamic type is also 
Super so, the compiler doesn’t know what to do in such a situation. Going back to 
the Master slave analogy, we have a proper Master here with both static and dynamic 
type as Master, thus when we ask it to do slave work, it says, “I don’t do no slave 
work!” (you can see how the Master picks up some slave idioms in the in the mean 
time…)

However if the casting was like this…

Super D= new Sub ( );
 ((Sub) D).methodx ( );

The everything is OK, as then the Master is cast into slave and it was a slave all
along! The dynamic type was Sub! We don’t even have to cast…as D was a slave by it’s 
dynamic type all along, and we know that dynamic type RULES!!!



Sub E = new Sub ();
((Super) E).methodx();

Here still, same stuff, just have to remember that dynamic type is what matters. We 
can cast the slave E to be the of the Master race but when he goes to work, we see 
that all he knows is slave work and none of the Master’s work. Thus, the methodx 
from the Sub class gets called. Since even though we case E, we just change the 
Static type by the cast, we can not change the Dynamic type and the dynamic type is 
still pointing at a Sub object…

So the take away point is:

1. Dynamic type is all that matters on method call, I mean non-static methods.
2. Sub class static type var can NOT point to Super objects.
3. Super static type var CAN point to Sub objects.

In terms of Casting:

1. Casting Super var to Sub is NOT OK, where the dynamic type was Super
2. Casting to Super of Sub var is OK, but doesn’t gain us anything, while 
         the dynamic type was Sub object anyway.


Simple clarity, left side of assignment is static type, right side is dynamic type
(which contains the ‘new’ keyword).

Saturday, October 20, 2007

Iterator Example


import java.util.*;

public class HashSetIterator {

 /**
  * @A.J, CH 15
  */
 public static void main(String[] args) {
  
  HashSet s = new HashSet();
  
  s.add("House");
  s.add("of");
  s.add("fun");
  s.add("believe");
  s.add("Shame");
  s.add("woke");
  
  System.out.println("The Set Contains: ");
  
  Iterator i = s.iterator();
  while (i.hasNext())
   System.out.println (i.next());
  
  System.out.println("****End of Contents***");
  i.remove();
  
  System.out.println();
  System.out.println("The Set _now_ Contains: ");
  
  Iterator z = s.iterator();
  while (z.hasNext())
   System.out.println (z.next());
  
  System.out.println("****End of Contents***");
  System.out.println();
  System.out.println();
  System.out.println("The Java Instructions have come to an END.");
  

 }

}

/*
The Set Contains: 
of
woke
House
fun
believe
Shame
****End of Contents***

The Set _now_ Contains: 
of
woke
House
fun
believe
****End of Contents***


The Java Instructions have come to an END.
*/

Wednesday, October 17, 2007

Java Library ArrayList


import java.io.PrintStream;
import java.util.*;

public class ReadAndReverse {

 
  static void readAndReverse (Scanner input, PrintStream output) {
   ArrayList L = new ArrayList ();
   while (input.hasNext())
    L.add(input.next());
   for (int k = L.size() - 1; k >= 0; k -=1)
    output.printf("%s ", L.get(k));
  }
  
  public static void main (String [] args) {
   Scanner inp = new Scanner (System.in);
   readAndReverse (inp, System.out);
  }
}

Thursday, October 11, 2007

Inserting into an array non-destructively

//insert into an array public void insert (int nInt, int pos) { myV[myCt] = myV [myC-1]; //increase the interesting sub-array size int k = myV.length ; for (int i = k-1; i >= 0; i--) { if (i == pos) { myV[i] = nInt; break; // done, get out! } myV[i] = myV[i-1]; //shift the values down } myCt++; //increase the instance var... }

Singly linked list operations...

public class IntList { // Names of simple Containers public int head; public IntList tail; // Constructor function /** List Cell containing (HEAD, TAIL). */ public IntList (int head, IntList tail) { this.head = head; //Scheme car this.tail = tail; //Scheme cdr } /* Converts an Array of Integers into a Linked List with * the same elements. * @param: an Array of integers with > 1 elements */ static IntList makeList (int a []) { IntList X, Z; X = new IntList (a[0], null); int i; for (i = 1, Z = X; i < a.length ; i++, Z = Z.tail){ Z.tail = new IntList (a[i], null); } return X; } /* Recursive Version */ static IntList makeListr (int a []) { int i = 0; IntList X, Z; X = new IntList (a[0], null); Z = X; Z = makelistrhelper (X, a, ++i); return X; } static IntList makelistrhelper (IntList Z, int a [], int i) { if (i > a.length -1 ){ return Z; } else { Z.tail = new IntList (a[i], null); return makelistrhelper (Z.tail, a, ++i); } } static int countList (IntList Z) { int countL = 0; countL = countListH (Z, countL); return countL; } static int countListH (IntList Z, int countL){ if (Z == null) return countL; else { return countListH (Z.tail, ++countL); } } static void printList (IntList Z) { int i = 0; IntList M; for (M = Z; M != null; M = M.tail ) { System.out.println("Head" + "-" + i +" ---- " + M.head); i++; } } /** List of all items in P incremented by n. */ static IntList incrList (IntList P, int n) { if (P == null) return null; else return new IntList (P.head+n, incrList (P.tail, n)); } /** Iterative version */ static IntList incrListIterative (IntList P, int n) { if (P == null) return null; IntList result, last; result = last = new IntList (P.head+n, null); while (P.tail != null) { P = P.tail; last.tail = new IntList (P.head+n, null); last = last.tail; } return result; } /** List of all items in P incremented by n. May destroy original. */ static IntList dincrList (IntList P, int n) { if (P == null) return null; else { P.head += n; P.tail = dincrList (P.tail, n); return P; } } /** For version */ static IntList forDincrList (IntList L, int n) { // for is more than a loooooooooper. for (IntList p = L; p != null; p = p.tail ) p.head += n; return L; } /** The List resulting from removing all instances of X * from L non-destructively */ static IntList removeAll (IntList L, int x){ if (L == null) return null; else if (L.head == x) return removeAll (L.tail, x); else return new IntList (L.head, removeAll (L.tail, x)); } static IntList removeAllIterative (IntList L, int x) { IntList result, last; result = last = null; for ( ; L != null; L = L.tail){ /* L != null and I is true. */ if (x == L.head) continue; else if (last == null) result = last = new IntList (L.head, null); else last = last.tail = new IntList (L.head, null); } return result; /** Here, I is the Loop Invariant: * Result of all elements of L0 not equal to X up to * and not including L, and last points to the last * elements of result, if any. We use L0 here to mean * "the original value of L." * */ } }

Tuesday, October 9, 2007

PascalTriangles once more!

Here we go again...Pascal Triangles once more...by popular demand only....
public class PascalTriangle { public static int [] [] pascalTriangle (int n) { int [][] pt = new int [n][]; for (int i = 0; i < n; i++){ pt[i] = new int [i + 1]; pt[i][0] = 1; for (int j = 1; j < i; j++) { pt[i][j] = pt[i - 1][j - 1] + pt [i -1][j]; } pt[i][i] = 1; } return pt; } public static void printTriangle (int x [][], int n) { for (int i = 0; i < n; i++){ System.out.println(); for (int k = 0; k <= i; k++ ) { System.out.print (" " + x[i][k]); } } } public static void getPascalTriangle (int n) { printTriangle (pascalTriangle (n), n); } public static void main(String[] args) { int G = 30; getPascalTriangle(G); } }

Sieve of Erotosthenes

The fabulous Sieve of EROTOSTHENES once more, if you are already not too sick of it by now!
public class PrintPrimes { public static void printPrimes (int n) { boolean [] prime = new boolean [n + 1]; int i; for (i=2; i <= n; i++ ) { prime[i] = true; } for (int divisor = 2; divisor * divisor <= n; divisor ++) { if (prime[divisor]) { for (i = 2* divisor; i <= n; i = i + divisor) { prime [i] = false; } } } for (i = 2; i <= n; i++ ) { if (prime[i]) { System.out.print (" " + i); } } } public static void main(String[] args) { int G = 10; PrintPrimes.printPrimes(G); } }

Monday, October 8, 2007

Linked List Constructor Functionality Testing

public class IntListTest { public static void main (String [] args) { int [] a = new int [] { 3, 6, 19, 71 }; IntList X = new IntList (0, null); X = X.makeList (a); System.out.println ("List created! "); X.printList(X); IntList Y = new IntList (0, null); int [] x = new int [] { 3, 2, 32, 57, 72, 98, 32, 323 , 232}; Y = Y.makeListr(x); System.out.println ("List created! "); Y.printList(Y); System.out.println ("List Count: " + Y.countList(Y)); } } %java IntListTest List created! Head-0 ---- 3 Head-1 ---- 6 Head-2 ---- 19 Head-3 ---- 71 List created! Head-0 ---- 3 Head-1 ---- 2 Head-2 ---- 32 Head-3 ---- 57 Head-4 ---- 72 Head-5 ---- 98 Head-6 ---- 32 Head-7 ---- 323 Head-8 ---- 232 List Count: 9

The Linked List Maker method

The methods missing from yesterday's post... public class IntList { // Names of simple Containers public int head; public IntList tail; // Constructor function /** List Cell containing (HEAD, TAIL). */ public IntList (int head, IntList tail) { this.head = head; //Scheme car this.tail = tail; //Scheme cdr } /* Converts an Array of Integers into a Linked List with * the same elements. * @param: an Array of integers with > 1 elements */ static IntList makeList (int a []) { IntList X, Z; X = new IntList (a[0], null); int i; for (i = 1, Z = X; i < z =" Z.tail){" tail =" new" i =" 0;" x =" new" z =" X;" z =" makelistrhelper"> a.length -1 ){ return Z; } else { Z.tail = new IntList (a[i], null); return makelistrhelper (Z.tail, a, ++i); } } static int countList (IntList Z) { int countL = 0; countL = countListH (Z, countL); return countL; } static int countListH (IntList Z, int countL){ if (Z == null) return countL; else { return countListH (Z.tail, ++countL); } } static void printList (IntList Z) { int i = 0; IntList M; for (M = Z; M != null; M = M.tail ) { System.out.println("Head" + "-" + i +" ---- " + M.head); i++; } } }

Just some daily notes ...

Powered By Blogger