Traversing a Linked List

/* This program sketch is showing several different approaches at once */ Last update 2/6/98

/* if the recusion is to be handled inside the List class,
   the Node definition wont need a print procedure..
   if it is handled by the Node class, see alternate definition below*/

class Node {
   Object data ;        
   Node link;
}     

////////////////////////////////////

class LinkList implements ListInterface {

  private Node Head ;

/*  ..... other stuff goes here ..... you did this in HW02 ...

  /*   // This is a way to traverse the list without using recursion
    public void print()                   // prints the list in order
    {                                     // this would simply use a "for" loop
      System.out.print("(");		  // could be done with "while" loop

      for ( Node T=Head; T != null; T=T.link)
	System.out.print(T.data + ",") ;

      System.out.println(")");
    }
  */



  private void printData( Node T ){  // A *PRIVATE* helping procedure for
                                     // a recursive approach ....
    if (T == null)
      ; // nothing
    else {
      System.out.print(T.data + ",") ;
      printData( T.link ) ;
    }
  }

    public void print()                   //   print the list in order
    {                                 
      System.out.print("(");
      printData(Head);
      System.out.println(")");
    }


  private void printDataInReverse( Node T ){ // A *PRIVATE* helping procedure 
    if (T == null)
      ; // nothing
    else {
      printDataInReverse( T.link ) ;
      System.out.print(T.data + ",") ;
    }
  }

    public void printReverse()               
    {
      System.out.print("(");
      printDataInReverse(Head);
      System.out.println(")");
    }

} // end of class definition





///////////////////// Alternate (better) approach as discussed in class 

class Node { 

  Object data ;    Node link;

  void PrintList() {          // a recursive approach, within Node
    if (this == null)
      ; // nothing
    else {
      System.out.print(this.data + ",") ;
      this.link.PrintList() ;             // I fixed this 2/6/98
    }
  }
}


...inside Linked list class, declare this :

    public void printFromNode()               
    {
      Head.PrintList() ;
    }






////// to USE  this stuff ..



public class TestLinkList {

  public static void main (String[] args) {

   LinkList L = new LinkList() ;

   String A= "1st"     ;  L.append(A)    ;  

   String B= "second!" ;  L.append(B) ;
   

   L.print() ;   

   L.printReverse() ;

   L.printFromNode() ;


   }  

}

  • Back to Java programs list