1.5.3 Inserting List Elements1.5.2 List Type1.5 Dynamic Data Structures1.5.4 Searching for List Elements

1.5.3 Inserting List Elements

The first operation is that of inserting a new element into a list. Let us for the moment assume that elements are always inserted at the head of the list. This allows us to define the method

  class List
  {
    ...
    void insert(int value)
    {
      Node node = new Node(value, head);
      head = node;
    }
  }

which allocates a new list node, sets its content to value, links it with the current head and then updates head to refer to the new node as the first node of the list. We can thus create the list [3,2,1] as

  List l = new List();
  l.insert(1);
  l.insert(2);
  l.insert(3);

To make the process of filling lists a bit more convenient, we may make insert a program function

  // ---------------------------------------------------------
  // list = insert(value)
  // 'list' is the result of inserting 'value' at the head of
  // 'this' list.
  //
  // Output
  //   'list == this'
  //   'list.head.value == value'
  //   'list.head.next == old this.head'
  //   all nodes referenced via 'old this' remain unchanged
  // ---------------------------------------------------------
  List insert(int value)
  {
    Node node = new Node(value, head);
    head = node;
    return this;
  }

which returns the list as its result. Then we can write

  List l = new List();
  l.insert(1).insert(2).insert(3);

which also gives list [3,2,1].


© Wolfgang Schreiner; February 3, 2005

1.5.3 Inserting List Elements1.5.2 List Type1.5 Dynamic Data Structures1.5.4 Searching for List Elements