Skip to main content
ICT
Lesson AB29 - Linked List
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

B. Methods for Manipulating Nodes page 4 of 16

  1. Methods for the ListNode class will consist of those for creating, accessing, and modifying nodes.

  2. The constructor for the ListNode class is responsible for creating a node and initializing the two instance variables of a new node.

    public ListNode(Object initValue, ListNode initNext) {
    // post: constructs a new element with object initValue,
    // followed by next element
      value = initValue;
      next = initNext;
    }

  3. Here is an example of code to create the first node of a linked list.

    ListNode first;
    first = new ListNode(new Integer(23), null);

    After execution of the two statements, first refers to the header node of a small linked list that contains just one node with the Integer 23.

  4. Getting and setting the data and link of the node are accomplished with getter and setter methods as follows.

    public Object getValue(){
    // post: returns value associated with this element
      return value;
    }

    public ListNode getNext(){
    // post: returns reference to next value in list

      return next;
    }

    public void setValue(Object theNewValue) {
      value = theNewValue;
    }

  5. public void setNext(ListNode theNewNext) {
    // post: sets reference to new next value
      next = theNewNext;
    }

  6. The following segment of code using ListNode will illustrate the syntax of accessing the data members of a ListNode.

    ListNode list;

    list = new ListNode(new Integer(13), null);

    System.out.println("The node contains: " +
                       (Integer)list.getValue());

    list.setValue(new Integer(17));
    System.out.println("The node contains: " +
                       (Integer)list.getValue());

    Run Output:

    The node contains: 13
    The node contains: 17

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.