SlideShare a Scribd company logo
1 of 110
Chapter 6
Methods for Making
 Data Structures



                     1
Dynamic Arrays in
             Data Structures
• In almost every data structure, we want
  functions for inserting and removing data.
• When dynamic arrays are used, the insertion
  function would add data to the array, while the
  removal function would “eliminate” data from the
  array (make it unusable).
• When the array becomes full, we would want to
  do an expansion – when many elements have
  been removed, we would want to do a
  contraction, so that only the used elements
  remain.
                                                     2
Array
        Expansion/Contraction
• One possible method:
  – When an element is inserted by the
    client, increase the size of the array by 1.
  – When an element is removed by the
    client, decrease the size of the array by 1.
• The problem with this method is that it is
  inefficient – every time an element is
  inserted or removed, the changeSize
  function is called…

                                                   3
changeSize Function
                                             33
0    1    2    3         432 433 444 445

25   75   10   12   …    56   32   73   87



                        New element needs to be
                        put into array, so
                        changeSize function is
                        called



                                                  4
changeSize Function
               (cont.)
0    1    2     3          432 433 444 445

25   75   10    12   …      56     32   73   87



0    1    2     3          432 433 444 445 446

                     …
               new array is made


                                                  5
changeSize Function
                    (cont.)
     0    1    2    3        432 433 444 445

     25   75   10   12   …    56   32   73   87



     0    1    2    3        432 433 444 445 446

     25   75   10   12   …    56   32   73   87

elements are copied over one by one using a for loop


                                                       6
changeSize Function
                     (cont.)
                                                        33




      0    1    2    3        432 433 444 445 446

      25   75   10   12   …    56   32   73   87   33


            Then, the new element can be put in
This process would take place every time a new element
needs to be inserted.                                  7
changeSize Function
                      (cont.)
      0    1    2     3        432 433 444 445 446

      25   75    10   12   …   56   32   73   87   33




Likewise, when an element needs to be removed, this
method contracts the array by one to conserve memory.


Suppose the element at the end of the array needs to be
removed.

                                                          8
changeSize Function
                      (cont.)
      0    1    2     3        432 433 444 445 446

      25   75    10   12   …    56   32   73   87   33


      0    1    2     3        432 433 444 445

                           …
The changeSize function is called and a new, smaller
array is made.

                                                         9
changeSize Function
                      (cont.)
      0    1    2     3        432 433 444 445 446

      25   75    10   12   …   56   32   73   87   33


      0    1    2     3        432 433 444 445

      25   75    10   12   …   56   32   73   87



The elements are copied over one by one, using a for
loop.

                                                        10
changeSize Function
                      (cont.)



      0    1    2     3        432 433 444 445

      25   75    10   12   …   56   32   73   87



This method of array expansion/contraction is largely
inefficient, because there is too much element copying.

                                                          11
Linked Structures
• Sometimes it is best to store data in a
  linked structure (an alternative to an
  Array)
• A linked structure consists of a group of
  nodes – each node is made from a struct.
• An object of the Node struct contains an
  element of data.



                                          12
A Node Struct
               Template
                              The info member is
                              for the data. It can
template <typename T>         anything (T), but it is
struct Node {                 often the object of
       T info;                another struct, used
       Node<T> *next;         as a record of
};                            information.
    The next pointer stores
    the address of a Node
    of the same type! This
    means that each node
    can point to another
    node.
                                                   13
Nodes
• In a data structure, each node is made in
  the heap; therefore, a node can only be
  accessed by a pointer.
• The client does not deal with nodes.
• When the client uses an insertion
  function, an element of data is passed into
  the insert function, and the function places
  it in a node.
                                             14
Nodes (cont.)
• When the client wants to retrieve data, the
  data in a node is returned to the client (but
  not the node itself).
• The node struct template exists for use by
  the data structure.




                                              15
Example of a
        Linked Structure

start




        Each blue node is divided into two
        sections, for the two members of
        the Node struct.



                                             16
Example of a
          Linked Structure (cont.)

start




        The left section is   The right section is the
        the info member.      pointer called “next”.




                                                         17
Example of a
         Linked Structure (cont.)

start




The start pointer would   The last node doesn’t
be saved in the private   point to another node, so
section of a data         its pointer (called next) is
structure class.          set to NULL (indicated by
                          slash).

                                                    18
Linked Lists
• The arrangement of nodes in the linked
  structure on the previous slide is often
  called a linked list.
• We can access any element of the linked
  list, for retrieval of information.
• We can also remove any element from the
  linked list (which would shorten the list).
• We can also insert any element into any
  position in the linked list.
                                            19
Linked List
             Advantages

…     5       3        7       2       1   …

    Removing an element from the
    middle of a linked list is fast.




                                           20
Linked List
          Advantages (cont.)

…     5       3                2       1   …

    Removing an element from the
    middle of a linked list is fast.




                                           21
Removal Problem in Array


     211 212 213 214 215 216 217 218
…     25   75   10   12   33   49   29   87   …

    Removing elements from the middle
    of an array (without leaving gaps) is
    more problematic.


                                                  22
Removal Problem in Array (cont.)


      211 212 213 214 215 216 217 218
 …     25   75   10     33   49   29   87   …

     A loop must be used to slide each
     element on the right one slot to the
     left, one at a time…


                                                23
Removal Problem in Array (cont.)
     211 212 213 214 215 216 217 218
 …   25   75   10   33        49   29   87   …
     211 212 213 214 215 216 217 218
 …   25   75   10   33   49        29   87   …
     211 212 213 214 215 216 217 218
 …   25   75   10   33   49   29        87   …
                                                 24
Removal Problem in Array (cont.)


     211 212 213 214 215 216 217 218
 …   25   75   10   33   49   29   87    …

                          Only 100,000 more to go!




                                                 25
Linked List
          Advantages (cont.)
• Linked lists also waste less memory for
  large elements (records of information).
• Wasted memory is memory space in the
  data structure not used for data.
• In arrays, the wasted memory is the part of
  the array not being utilized.
• In linked lists, the wasted memory is the
  pointer in each node.
                                           26
Linked List
        Advantages (cont.)

start

            Linked List




             Array

                             27
Accessing info
start



  To access the info in the first node:

         (*start).info

  Or (better yet)
                          dereference and member
         start->info      access in one shot

                                                   28
Accessing info
                    (cont.)
start



  To access the info in the second node:

        start->next->info




                                           29
Finding a Possible
                  Mercedes
start                            item
                                        maker: Mercedes
                                        price:



                      Mercedes
               …                        year:
                                        operator ==


  Let’s solve the problem, but let’s assume that item
  is passed in as a parameter (of type T). This is
  normally what would happen.
  Instead of the CarType struct having an overloaded
  != operator, it will have an overloaded == operator.

                                                         30
Finding a Possible
                    Mercedes (cont.)
start                                        item
                                                     maker: Mercedes
                                                     price:



                              Mercedes
                        …                            year:
                                                     operator ==
CarType item;
item.maker = "Mercedes";
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
         if ( ptr->info == item ) // overloaded ==
                    found = true;
         if ( !found )
                    ptr = ptr->next;
                                                                   31
}
Finding a Possible
                    Mercedes (cont.)
start     ptr                                item
                                                     maker: Mercedes
                                                     price:



                              Mercedes
                     …                               year:
                                                     operator ==
CarType item;
item.maker = "Mercedes";
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
         if ( ptr->info == item ) // overloaded ==
                    found = true;
         if ( !found )
                    ptr = ptr->next;
                                                                   32
}
Finding a Possible
                     Mercedes (cont.)
start     ptr                                  item
                                                       maker: Mercedes
                                                       price:



                                Mercedes
                        …                              year:
                                                       operator ==
CarType item;
item.maker = "Mercedes";                             found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
         if ( ptr->info == item ) // overloaded ==
                    found = true;
         if ( !found )
                    ptr = ptr->next;
}                                                                    33
Finding a Possible
                    Mercedes (cont.)
start    ptr                                  item
                                                      maker: Mercedes
                                                      price:



                               Mercedes
                        …                             year:
                                                      operator ==
CarType item;
item.maker = "Mercedes";                            found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
        if ( ptr->info == item ) // overloaded ==
                   found = true;
        if ( !found )
                   ptr = ptr->next;
}                                                                   34
Finding a Possible
                    Mercedes (cont.)
start    ptr                               item
                                                  maker: Mercedes
                                                  price:



                                Mercedes
                      …                           year:
                                                  operator ==
CarType item;
item.maker = "Mercedes";                     found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
        if ( ptr->info == item ) // overloaded ==
                  found = true;
        if ( !found )
                  ptr = ptr->next;
}                                                               35
Finding a Possible
                    Mercedes (cont.)
start     ptr                             item
                                                 maker: Mercedes
                                                 price:



                               Mercedes
                      …                          year:
                                                 operator ==
CarType item;
item.maker = "Mercedes";                    found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
         if ( ptr->info == item )
                    found = true;
        if ( !found )
                 ptr = ptr->next;
}                                                              36
Finding a Possible
                    Mercedes (cont.)
start     ptr                             item
                                                 maker: Mercedes
                                                 price:



                               Mercedes
                      …                          year:
                                                 operator ==
CarType item;
item.maker = "Mercedes";                    found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
         if ( ptr->info == item )
                    found = true;
         if ( !found )
                 ptr = ptr->next;
}                                                              37
Finding a Possible
                     Mercedes (cont.)
start    ptr                                item
                                                   maker: Mercedes
                                                   price:



                                 Mercedes
                        …                          year:
                                                   operator ==
CarType item;
item.maker = "Mercedes";                      found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
        if ( ptr->info == item )
                   found = true;
        if ( !found )
                   ptr = ptr->next;
}                                                                38
Finding a Possible
                    Mercedes (cont.)
start    ptr                               item
                                                  maker: Mercedes
                                                  price:



                                Mercedes
                      …                           year:
                                                  operator ==
CarType item;
item.maker = "Mercedes";                     found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
        if ( ptr->info == item ) // overloaded ==
                  found = true;
        if ( !found )
                  ptr = ptr->next;
}                                                               39
Finding a Possible
                    Mercedes (cont.)
start     ptr                             item
                                                 maker: Mercedes
                                                 price:



                               Mercedes
                      …                          year:
                                                 operator ==
CarType item;
item.maker = "Mercedes";                    found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
         if ( ptr->info == item )
                    found = true;
        if ( !found )
                 ptr = ptr->next;
                                                               40
}
Finding a Possible
                    Mercedes (cont.)
start                        ptr           item
                                                  maker: Mercedes
                                                  price:



                                Mercedes
                        …                         year:
                                                  operator ==
CarType item;
item.maker = "Mercedes";                     found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) { After going through the
       if ( ptr->info == item )  loop several times…
                  found = true;
        if ( !found )
                  ptr = ptr->next;
}                                                               41
Finding a Possible
                    Mercedes (cont.)
start                        ptr           item
                                                  maker: Mercedes
                                                  price:



                                Mercedes
                      …                           year:
                                                  operator ==
CarType item;
item.maker = "Mercedes";                     found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {           Notice that found is
        if ( ptr->info == item )           only set to true if ptr
                 found = true;             is not NULL and
        if ( !found )                      Mercedes is found …
                  ptr = ptr->next;
                                                                 42
}
Finding a Possible
                     Mercedes (cont.)
start                         ptr           item
                                                   maker: Mercedes
                                                   price:



                                 Mercedes
                        …                          year:
                                                   operator ==
CarType item;
item.maker = "Mercedes";                      found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
        if ( ptr->info == item )            then, !found is false
                   found = true;            and the loop exits
        if ( !found )
                   ptr = ptr->next;
}                                                                   43
What If Mercedes Does Not Exist?
start                               ptr   item
                                                 maker: Mercedes
                                                 price:
                      …                          year:
                                                 operator ==
CarType item;
item.maker = "Mercedes";                     found: false
Node<T> *ptr = start;
bool found = false;                       If Mercedes is not found,
while (ptr != NULL && !found ) {
         if ( ptr->info == item )
                                          ptr eventually gets set to
                    found = true;         NULL.
        if ( !found )
                 ptr = ptr->next;
}                                                                44
What If Mercedes Does not Exist?
                 (cont.)
start          ptr is set to NULL   item
                                           maker: Mercedes
                                           price:
                      …                    year:
                                           operator ==
CarType item;
item.maker = "Mercedes";               found: false
Node<T> *ptr = start;
bool found = false;                 If Mercedes is not
while (ptr != NULL && !found ) {
         if ( ptr->info == item )
                                    found, ptr eventually
                    found = true;   gets set to NULL.
         if ( !found )
                 ptr = ptr->next;
}                                                           45
What If Mercedes Does not Exist?
                 (cont.)
start          ptr is set to NULL     item
                                             maker: Mercedes
                                             price:
                        …                    year:
                                             operator ==
CarType item;
item.maker = "Mercedes";                found: false
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {       Exit from loop
        if ( ptr->info == item )       because ptr is
                   found = true;       NULL.
        if ( !found )
                   ptr = ptr->next;
}                                                          46
What If Finding in an Empty Linked
               List?
• When a linked list is empty, the start
  pointer should always be set to NULL.
• The start pointer would be set to NULL
  inside the constructor, when an empty
  linked list is first made.




                                           47
Finding in an Empty List
                                   item
start is set to NULL                      maker: Mercedes
                                          price:
                                          year:
                                          operator ==
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
       if ( ptr->info == item )
                found = true;             SAME CODE
       if ( !found )
                ptr = ptr->next;
}
                                                            48
Finding in an Empty List (cont.)
                                   item
start is set to NULL                      maker: Mercedes
ptr is set to NULL                        price:
                                          year:
                                          operator ==
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {
       if ( ptr->info == item )
                found = true;
       if ( !found )
                ptr = ptr->next;
}
                                                            49
Finding in an Empty List (cont.)
                                   item
start is set to NULL                      maker: Mercedes
ptr is set to NULL                        price:
                                          year:
                                          operator ==
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) {      found: false
       if ( ptr->info == item )
                found = true;
       if ( !found )
                ptr = ptr->next;
}
                                                            50
Finding in an Empty List (cont.)
                                  item
start is set to NULL                      maker: Mercedes
ptr is set to NULL                        price:
                                          year:
                                          operator ==
Node<T> *ptr = start;
bool found = false;
while (ptr != NULL && !found ) { found: false
      if ( ptr->info == item )
               found = true;             Exit loop
      if ( !found )                      because ptr is
               ptr = ptr->next;          NULL.
}
                                                            51
Inserting a New Node
• Let’s assume that we want to insert a new
  node at the beginning of a linked list.
• Assume that the client passes in a
  parameter called element (of type T).
• We would like to place the element into a
  node and insert the node at the beginning
  of the linked list.


                                          52
Inserting a Node at Front
                                      element


start



        All new nodes must be made in the heap, SO…




                                                      53
Inserting a Node at Front (cont.)
                                        element


  start



ptr


          Node<T> *ptr = new Node<T>;



                                                  54
Inserting a Node at Front (cont.)
                                        element


  start



ptr


          Node<T> *ptr = new Node<T>;

 Now we have to store element into the node

                                                  55
Inserting a Node at Front (cont.)
                                        element


  start



ptr


          Node<T> *ptr = new Node<T>;
          ptr->info = element;

                                                  56
Inserting a Node at Front (cont.)
                                          element


  start

                 Now we have to think about how to
ptr              make the pointer called “next” point to
                 the first node in the list, to link it in

          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                        57
Inserting a Node at Front (cont.)
                                         element


  start


               You can’t successfully write code like
ptr            this without thinking about addresses.


          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                        58
Inserting a Node at Front (cont.)
                                         element


  start

                 REMEMBER…when you want to
ptr              change the way a pointer points, you
                 HAVE to assign a different address to it

          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                       59
Inserting a Node at Front (cont.)
                                        element


  start

                 Right now, the pointer called “next”
ptr              doesn’t have a valid address assigned
                 to it.

          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                     60
Inserting a Node at Front (cont.)
                                         element


  start


                To store the correct address in it, we
ptr             have to find the address of the first node
                of the linked list.
          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                       61
Inserting a Node at Front (cont.)
                                        element


  start



ptr               Where is the address of the first node
                  stored?

          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                      62
Inserting a Node at Front (cont.)
                                        element


  start

                Now think, the address would be stored
ptr             in something that points to it. So where
                is it stored?

          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                      63
Inserting a Node at Front (cont.)
                                           element


  start



ptr               That’s right, in the start pointer.


          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                        64
Inserting a Node at Front (cont.)
                                         element


  start



ptr            So now, all we have to do is copy that
               address into the pointer called “next”

          Node<T> *ptr = new Node<T>;
          ptr->info = element;


                                                        65
Inserting a Node at Front (cont.)
                               element


  start



ptr


 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
                                         66
Inserting a Node at Front (cont.)
                                     element


  start



ptr             Well, it’s been inserted. But start
                should point to the first node now.


 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
                                                  67
Inserting a Node at Front (cont.)
                                       element


  start


               REMEMBER…when you want to
ptr            change the way a pointer points, you
               have to assign a different address to it

 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
                                                     68
Inserting a Node at Front (cont.)
                                    element


  start


                We’d like start to point to the new
ptr             node, so what stores the address of
                the new node?

 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
                                                 69
Inserting a Node at Front (cont.)
                                      element


  start


               That’s right, ptr. So now all we have
ptr            to do is assign the address stored in
               ptr to the start pointer.

 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
                                                       70
Inserting a Node at Front (cont.)
                               element


  start



ptr


 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
 start = ptr;
                                         71
Inserting a Node at Front (cont.)
                                element


  start



ptr              Easy, right?

 Node<T> *ptr = new Node<T>;
 ptr->info = element;
 ptr->next = start;
 start = ptr;
                                          72
REMEMBER…
• Use drawings when working with linked
  lists, until you become an expert.
• When you want to change the way a
  pointer points, you have to assign a
  different address to it.
• You can find the address you need by
  looking at other pointers (remember that
  they store addresses).
                                             73
Inserting into the Middle
           of a Linked List

• Suppose we know that there is a
  Mercedes in a linked list.
• We would like to insert a node containing
  Honda right after it.
• We first find the Mercedes, using code that
  we looked at before.


                                            74
Inserting a Node at Middle
start            ptr              element
                                            maker: Mercedes
                                            price:



                       Mercedes
                …                           year:
                                            operator !=


    After this code executes, ptr points to the
    node that has Mercedes.

 Node<T> *ptr = start;
 while ( ptr->info != element ) // element is a parameter
        ptr = ptr->next;
                                                              75
Inserting a Node at Middle (cont.)
start           ptr              element
                                           maker: Mercedes
                                           price:



                      Mercedes
               …                           year:
                                           operator !=



 Now we would like to insert a CarType object
 called elementToInsert (containing Honda), which
 would also be passed in as a parameter, right after
 the Mercedes


                                                             76
Inserting a Node at Middle (cont.)
start          ptr
                                    maker: Honda
                                    price: 5000



                     Mercedes
              …                     year: 1985
                                    operator !=


                                          elementToInsert

Well, all new nodes are created in the heap, SO…..



                                                     77
Inserting a Node at Middle (cont.)
start      ptr
                             maker: Honda
                             price: 5000



                  Mercedes
           …                 year: 1985
                             operator !=


        newNode                   elementToInsert

Node<T> *newNode = new Node<T>;



                                            78
Inserting a Node at Middle (cont.)
 start           ptr
                                    maker: Honda
                                    price: 5000



                       Mercedes
                …                   year: 1985
                                    operator !=


            newNode                       elementToInsert

  Node<T> *newNode = new Node<T>;
Now, how about placing elementToInsert into the new
node?
                                                      79
Inserting a Node at Middle (cont.)
start        ptr
                                  maker: Honda
                                  price: 5000



                   Mercedes
            …                     year: 1985
                                  operator !=


         newNode                       elementToInsert

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                 80
Inserting a Node at Middle (cont.)
start        ptr
                                  maker: Honda
                                  price: 5000



                   Mercedes
            …                     year: 1985
                                  operator !=


         newNode                       elementToInsert

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                 81
Inserting a Node at Middle (cont.)
start         ptr
                               Now, what we want is




                    Mercedes
                               shown by the dashed
             …
                               arrows; this would
                               cause the insertion of
                               the node
          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                  82
Inserting a Node at Middle (cont.)
start         ptr
                                   We have two
                                   pointers we need to



                    Mercedes
             …                     change – but we
                                   have to be careful
                                   about the way we
                                   change them
          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                   83
Inserting a Node at Middle (cont.)
start         ptr
                                   If we change the
                                   left pointer first,



                    Mercedes
             …                     we will no longer
                                   be able to access
                                   the last node
                                   (memory leak)
          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                         84
Inserting a Node at Middle (cont.)
start         ptr
                               So, we first have to
                               assign the address



                    Mercedes
             …                 of the last node into
                               the “next” pointer
                               of the new node
          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                  85
Inserting a Node at Middle (cont.)
start         ptr

                               Where is the



                    Mercedes
             …                 address of the last
                               node stored?

          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                 86
Inserting a Node at Middle (cont.)
start         ptr

                                   That’s right, it is



                    Mercedes
             …                     stored in ptr->next


          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;


                                                     87
Inserting a Node at Middle (cont.)
start         ptr




                    Mercedes
             …



          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;
newNode->next = ptr->next;

                                       88
Inserting a Node at Middle (cont.)
start         ptr




                    Mercedes
                    Mercedes
             …



          newNode

Node<T> *newNode = new Node<T>;
newNode->info = elementToInsert;
newNode->next = ptr->next;
ptr->next = newNode;
                                       89
Removing a Node
• Suppose we definitely know there is a
  Mercedes in the linked list and we wish to
  remove the node that contains it.
• We need to find the node first.




                                               90
Removing the First Node
      start
       Mercedes




                       …



                 Mercedes is in the first node
Node<T> *ptr = start;
if ( ptr->info == element )
         start = start->next;

                                                 91
Removing the First Node
                   (cont.)
      start
        Mercedes   ptr



                          …



Node<T> *ptr = start;
if ( ptr->info == element )
         start = start->next;


                                      92
Removing the First Node
                  (cont.)
     start
       Mercedes   ptr



                        …



Node<T> *ptr = start;
if ( ptr->info == element )
      start = start->next;


                                     93
Removing the First Node
                   (cont.)
        Mercedes   ptr   start



                            …



Node<T> *ptr = start;
if ( ptr->info == element )
       start = start->next;


                                      94
Removing the First Node
                (cont.)
               ptr   start



                         …



Node<T> *ptr = start;           Well, start points to the
if ( ptr->info == element ) {   beginning of the new
         start = start->next;   linked list, but a node isn’t
       delete ptr;              removed unless we free it.
}
                                                          95
Removing the First Node
                (cont.)
               ptr   start



                         …



Node<T> *ptr = start;           Now, let’s consider the
if ( ptr->info == element ) {   other case whereby
         start = start->next;
                                Mercedes is in the
         delete ptr;            middle of the list.
}
                                                      96
Removing a Middle Node
          start                  ptr




                                          Mercedes
                           …


else {
                                                     The while loop
         while ( ptr->next->info != element )
                                                     points ptr to the
                ptr = ptr->next;
                                                     node BEFORE
                                                     the node that
                                                     has Mercedes.
                                                                    97
Removing a Middle Node (cont.)
          start                ptr




                                        Mercedes
                          …


else {
         while ( ptr->next->info != element ) We need to join the
                ptr = ptr->next;              node before
                                              Mercedes to the
                                              node after
                                              Mercedes
                                                             98
Removing a Middle Node (cont.)
          start                ptr       ptr2




                                        Mercedes
                          …


else {
         while ( ptr->next->info != element )
                                              But we mus keep
                ptr = ptr->next;
                                              a pointer to the
                                              node that has
         Node<T> *ptr2 = ptr->next;
                                              Mercedes
                                                            99
Removing a Middle Node (cont.)
           start                          ptr     ptr2




                                                 Mercedes
                                   …


else {
          while ( ptr->next->info != element )
                    ptr = ptr->next;                        We now join the
                                                            node before
          Node<T> *ptr2 = ptr->next;                        Mercedes to the
          ptr->next = ptr2->next;                           node after
                                                            Mercedes
                                                                          100
Removing a Middle Node (cont.)
           start                          ptr      ptr2



                                   …


else {
          while ( ptr->next->info != element )
                    ptr = ptr->next;
                                                 We then delete the
          Node<T> *ptr2 = ptr->next;
          ptr->next = ptr2->next;                node that has Mercedes
          delete ptr2;
                                                 We did it!
                                                                    101
What If Mercedes is the Last
            Node?
• Would our code still work?
• Try to consider every possible situation in
  code design.




                                            102
Removing the Last
                             Node
           start                        ptr




                                                Mercedes
                            …


else {
         while ( ptr->next->info != element ) After looping, ptr
                   ptr = ptr->next;           stops on the
                                              next-to-the-last
         Node<T> *ptr2 = ptr->next;           node
         ptr->next = ptr2->next;
         delete ptr2;
         }

                                                             103
Removing the Last
                        Node (cont.)
           start                                ptr   ptr2




                                                      Mercedes
                                   …


else {
         while ( ptr->next->info != element )
                   ptr = ptr->next;

         Node<T> *ptr2 = ptr->next;
         ptr->next = ptr2->next;
         delete ptr2;
         }


                                                                 104
Removing the Last
                          Node (cont.)
           start                                ptr   ptr2




                                                      Mercedes
                                   …


else {
         while ( ptr->next->info != element )
                   ptr = ptr->next;

         Node<T> *ptr2 = ptr->next;
         ptr->next = ptr2->next;
         delete ptr2;
         }


                                                                 105
Removing the Last
                        Node (cont.)
             start                              ptr   ptr2


                                   …


else {
         while ( ptr->next->info != element )   The code works
                   ptr = ptr->next;
                                                in removing the
         Node<T> *ptr2 = ptr->next;             last node.
         ptr->next = ptr2->next;
         delete ptr2;
         }


                                                                  106
Working With Linked Lists
• As you can see, sometimes you have to
  do a lot of thinking and problem-solving
  when working with linked lists.
• It is not always obvious how to write code.
• You can’t memorize the code, because it
  will not quite fit situations that you will
  encounter.
• It is a matter of using logic (and knowing a
  few tricks of the trade).
                                             107
Code for Removing
                 a Node
1 Node<T> *ptr = start;               Here is the resulting
2 if ( ptr->info == element ) {       code for removing a
3       start = start->next;          node. It is assumes
4       delete ptr;                   the node we are
5       }                             looking for is in the
6 else {                              linked list.
7       while ( ptr->next->info != element )
8               ptr = ptr->next;
9       Node<T> *ptr2 = ptr->next;
10      ptr->next = ptr2->next;
11      delete ptr2;
12      }
                                                         108
Speed
• In some situations, an array can be faster than a
  linked list, such as when a calculated index is
  used to access an element.
• In other situations, a linked list can be faster
  than an array, such as when removing an
  element from the middle (as we saw before).
  – we usually need to search for the element to
    remove, but we search for it in both the array and
    linked list.


                                                         109
Reference
• Childs, J. S. (2008). Methods for Making
  Data Structures. C++ Classes and Data
  Structures. Prentice Hall.




                                             110

More Related Content

What's hot

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL乐群 陈
 
08 ds and algorithm session_11
08 ds and algorithm session_1108 ds and algorithm session_11
08 ds and algorithm session_11Niit Care
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10Vince Vo
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30Mahmoud Samir Fayed
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data StructureChan Shik Lim
 
03 ds and algorithm session_04
03 ds and algorithm session_0403 ds and algorithm session_04
03 ds and algorithm session_04Niit Care
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in pythonLifna C.S
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsAnton Astashov
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 

What's hot (20)

Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
08 ds and algorithm session_11
08 ds and algorithm session_1108 ds and algorithm session_11
08 ds and algorithm session_11
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
 
The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30The Ring programming language version 1.4 book - Part 9 of 30
The Ring programming language version 1.4 book - Part 9 of 30
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
03 ds and algorithm session_04
03 ds and algorithm session_0403 ds and algorithm session_04
03 ds and algorithm session_04
 
Java unit i
Java unit iJava unit i
Java unit i
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Java
JavaJava
Java
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Java arrays
Java   arraysJava   arrays
Java arrays
 
Generics
GenericsGenerics
Generics
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScripts
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 

Viewers also liked

Ch08 evaluating arguments
Ch08 evaluating argumentsCh08 evaluating arguments
Ch08 evaluating argumentsHariz Mustafa
 
Bassham3 powerpoint lecturenotes_ch05
Bassham3 powerpoint lecturenotes_ch05Bassham3 powerpoint lecturenotes_ch05
Bassham3 powerpoint lecturenotes_ch05Hariz Mustafa
 
Cognition and problem_solving
Cognition and problem_solvingCognition and problem_solving
Cognition and problem_solvingHariz Mustafa
 
Lecture03 inheritance
Lecture03 inheritanceLecture03 inheritance
Lecture03 inheritanceHariz Mustafa
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programmingHariz Mustafa
 
Chapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_iiChapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_iiHariz Mustafa
 
Lecture04 polymorphism
Lecture04 polymorphismLecture04 polymorphism
Lecture04 polymorphismHariz Mustafa
 
Chapter 5 fallacies
Chapter 5 fallaciesChapter 5 fallacies
Chapter 5 fallaciesscrasnow
 
Bassham3 powerpoint lecturenotes_ch06
Bassham3 powerpoint lecturenotes_ch06Bassham3 powerpoint lecturenotes_ch06
Bassham3 powerpoint lecturenotes_ch06Hariz Mustafa
 
Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...
Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...
Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...XixiViolet
 
Ch03 basic logical_concepts
Ch03 basic logical_conceptsCh03 basic logical_concepts
Ch03 basic logical_conceptsHariz Mustafa
 
Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3Hariz Mustafa
 

Viewers also liked (15)

Lecture09 recursion
Lecture09 recursionLecture09 recursion
Lecture09 recursion
 
Lecture10 trees v3
Lecture10 trees v3Lecture10 trees v3
Lecture10 trees v3
 
Decision making
Decision makingDecision making
Decision making
 
Ch08 evaluating arguments
Ch08 evaluating argumentsCh08 evaluating arguments
Ch08 evaluating arguments
 
Bassham3 powerpoint lecturenotes_ch05
Bassham3 powerpoint lecturenotes_ch05Bassham3 powerpoint lecturenotes_ch05
Bassham3 powerpoint lecturenotes_ch05
 
Cognition and problem_solving
Cognition and problem_solvingCognition and problem_solving
Cognition and problem_solving
 
Lecture03 inheritance
Lecture03 inheritanceLecture03 inheritance
Lecture03 inheritance
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
Chapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_iiChapter 6 logical_fallacies_ii
Chapter 6 logical_fallacies_ii
 
Lecture04 polymorphism
Lecture04 polymorphismLecture04 polymorphism
Lecture04 polymorphism
 
Chapter 5 fallacies
Chapter 5 fallaciesChapter 5 fallacies
Chapter 5 fallacies
 
Bassham3 powerpoint lecturenotes_ch06
Bassham3 powerpoint lecturenotes_ch06Bassham3 powerpoint lecturenotes_ch06
Bassham3 powerpoint lecturenotes_ch06
 
Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...
Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...
Critical thinking fall 2014 2015 (chapters 6,7,8,11 and 12 analyzing and eval...
 
Ch03 basic logical_concepts
Ch03 basic logical_conceptsCh03 basic logical_concepts
Ch03 basic logical_concepts
 
Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3Exercise answers chapter 1, 2 & 3
Exercise answers chapter 1, 2 & 3
 

Similar to Lecture06 methods for-making_data_structures_v2

Chapter 12 - Heaps.ppt
Chapter 12 - Heaps.pptChapter 12 - Heaps.ppt
Chapter 12 - Heaps.pptMouDhara1
 
Principal Component Analysis(PCA) understanding document
Principal Component Analysis(PCA) understanding documentPrincipal Component Analysis(PCA) understanding document
Principal Component Analysis(PCA) understanding documentNaveen Kumar
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
DSP IEEE paper
DSP IEEE paperDSP IEEE paper
DSP IEEE paperprreiya
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformMartin Zapletal
 
Lecture 12
Lecture 12Lecture 12
Lecture 12Rana Ali
 
Lesson 2 Understanding Types And Usage In Dot Net
Lesson 2    Understanding Types And Usage In Dot NetLesson 2    Understanding Types And Usage In Dot Net
Lesson 2 Understanding Types And Usage In Dot Netnbaveja
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data ScienceMike Anderson
 
MetaPerturb: Transferable Regularizer for Heterogeneous Tasks and Architectures
MetaPerturb: Transferable Regularizer for Heterogeneous Tasks and ArchitecturesMetaPerturb: Transferable Regularizer for Heterogeneous Tasks and Architectures
MetaPerturb: Transferable Regularizer for Heterogeneous Tasks and ArchitecturesMLAI2
 
Oleksandr Obiednikov “Affine transforms and how CNN lives with them”
Oleksandr Obiednikov “Affine transforms and how CNN lives with them”Oleksandr Obiednikov “Affine transforms and how CNN lives with them”
Oleksandr Obiednikov “Affine transforms and how CNN lives with them”Lviv Startup Club
 
#GDC15 Code Clinic
#GDC15 Code Clinic#GDC15 Code Clinic
#GDC15 Code ClinicMike Acton
 
SenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige WhiteSenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige WhiteSencha
 
Angular.js Directives for Interactive Web Applications
Angular.js Directives for Interactive Web ApplicationsAngular.js Directives for Interactive Web Applications
Angular.js Directives for Interactive Web ApplicationsBrent Goldstein
 

Similar to Lecture06 methods for-making_data_structures_v2 (20)

Chapter 12 - Heaps.ppt
Chapter 12 - Heaps.pptChapter 12 - Heaps.ppt
Chapter 12 - Heaps.ppt
 
Principal Component Analysis(PCA) understanding document
Principal Component Analysis(PCA) understanding documentPrincipal Component Analysis(PCA) understanding document
Principal Component Analysis(PCA) understanding document
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Data structures
Data structuresData structures
Data structures
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
DSP IEEE paper
DSP IEEE paperDSP IEEE paper
DSP IEEE paper
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive Platform
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Lesson 2 Understanding Types And Usage In Dot Net
Lesson 2    Understanding Types And Usage In Dot NetLesson 2    Understanding Types And Usage In Dot Net
Lesson 2 Understanding Types And Usage In Dot Net
 
lecture4.pdf
lecture4.pdflecture4.pdf
lecture4.pdf
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
 
MetaPerturb: Transferable Regularizer for Heterogeneous Tasks and Architectures
MetaPerturb: Transferable Regularizer for Heterogeneous Tasks and ArchitecturesMetaPerturb: Transferable Regularizer for Heterogeneous Tasks and Architectures
MetaPerturb: Transferable Regularizer for Heterogeneous Tasks and Architectures
 
Ffst
FfstFfst
Ffst
 
Oleksandr Obiednikov “Affine transforms and how CNN lives with them”
Oleksandr Obiednikov “Affine transforms and how CNN lives with them”Oleksandr Obiednikov “Affine transforms and how CNN lives with them”
Oleksandr Obiednikov “Affine transforms and how CNN lives with them”
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
#GDC15 Code Clinic
#GDC15 Code Clinic#GDC15 Code Clinic
#GDC15 Code Clinic
 
SenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige WhiteSenchaCon 2016: The Once and Future Grid - Nige White
SenchaCon 2016: The Once and Future Grid - Nige White
 
Angular.js Directives for Interactive Web Applications
Angular.js Directives for Interactive Web ApplicationsAngular.js Directives for Interactive Web Applications
Angular.js Directives for Interactive Web Applications
 
Data miningpresentation
Data miningpresentationData miningpresentation
Data miningpresentation
 

More from Hariz Mustafa

More from Hariz Mustafa (12)

Topic6decisionmaking
Topic6decisionmakingTopic6decisionmaking
Topic6decisionmaking
 
Topic5cognition and problem_solving
Topic5cognition and problem_solvingTopic5cognition and problem_solving
Topic5cognition and problem_solving
 
Topic2 argument
Topic2 argumentTopic2 argument
Topic2 argument
 
Topic2
Topic2Topic2
Topic2
 
Topic 1
Topic 1Topic 1
Topic 1
 
Problem solving activities
Problem solving activitiesProblem solving activities
Problem solving activities
 
Decision making scenarios
Decision making scenariosDecision making scenarios
Decision making scenarios
 
Chapter 4 language
Chapter 4 languageChapter 4 language
Chapter 4 language
 
Chapter 5 logical_fallacies_i
Chapter 5 logical_fallacies_iChapter 5 logical_fallacies_i
Chapter 5 logical_fallacies_i
 
Bassham3 powerpoint lecturenotes_ch04
Bassham3 powerpoint lecturenotes_ch04Bassham3 powerpoint lecturenotes_ch04
Bassham3 powerpoint lecturenotes_ch04
 
6a
6a6a
6a
 
3a
3a3a
3a
 

Lecture06 methods for-making_data_structures_v2

  • 1. Chapter 6 Methods for Making Data Structures 1
  • 2. Dynamic Arrays in Data Structures • In almost every data structure, we want functions for inserting and removing data. • When dynamic arrays are used, the insertion function would add data to the array, while the removal function would “eliminate” data from the array (make it unusable). • When the array becomes full, we would want to do an expansion – when many elements have been removed, we would want to do a contraction, so that only the used elements remain. 2
  • 3. Array Expansion/Contraction • One possible method: – When an element is inserted by the client, increase the size of the array by 1. – When an element is removed by the client, decrease the size of the array by 1. • The problem with this method is that it is inefficient – every time an element is inserted or removed, the changeSize function is called… 3
  • 4. changeSize Function 33 0 1 2 3 432 433 444 445 25 75 10 12 … 56 32 73 87 New element needs to be put into array, so changeSize function is called 4
  • 5. changeSize Function (cont.) 0 1 2 3 432 433 444 445 25 75 10 12 … 56 32 73 87 0 1 2 3 432 433 444 445 446 … new array is made 5
  • 6. changeSize Function (cont.) 0 1 2 3 432 433 444 445 25 75 10 12 … 56 32 73 87 0 1 2 3 432 433 444 445 446 25 75 10 12 … 56 32 73 87 elements are copied over one by one using a for loop 6
  • 7. changeSize Function (cont.) 33 0 1 2 3 432 433 444 445 446 25 75 10 12 … 56 32 73 87 33 Then, the new element can be put in This process would take place every time a new element needs to be inserted. 7
  • 8. changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 25 75 10 12 … 56 32 73 87 33 Likewise, when an element needs to be removed, this method contracts the array by one to conserve memory. Suppose the element at the end of the array needs to be removed. 8
  • 9. changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 25 75 10 12 … 56 32 73 87 33 0 1 2 3 432 433 444 445 … The changeSize function is called and a new, smaller array is made. 9
  • 10. changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 25 75 10 12 … 56 32 73 87 33 0 1 2 3 432 433 444 445 25 75 10 12 … 56 32 73 87 The elements are copied over one by one, using a for loop. 10
  • 11. changeSize Function (cont.) 0 1 2 3 432 433 444 445 25 75 10 12 … 56 32 73 87 This method of array expansion/contraction is largely inefficient, because there is too much element copying. 11
  • 12. Linked Structures • Sometimes it is best to store data in a linked structure (an alternative to an Array) • A linked structure consists of a group of nodes – each node is made from a struct. • An object of the Node struct contains an element of data. 12
  • 13. A Node Struct Template The info member is for the data. It can template <typename T> anything (T), but it is struct Node { often the object of T info; another struct, used Node<T> *next; as a record of }; information. The next pointer stores the address of a Node of the same type! This means that each node can point to another node. 13
  • 14. Nodes • In a data structure, each node is made in the heap; therefore, a node can only be accessed by a pointer. • The client does not deal with nodes. • When the client uses an insertion function, an element of data is passed into the insert function, and the function places it in a node. 14
  • 15. Nodes (cont.) • When the client wants to retrieve data, the data in a node is returned to the client (but not the node itself). • The node struct template exists for use by the data structure. 15
  • 16. Example of a Linked Structure start Each blue node is divided into two sections, for the two members of the Node struct. 16
  • 17. Example of a Linked Structure (cont.) start The left section is The right section is the the info member. pointer called “next”. 17
  • 18. Example of a Linked Structure (cont.) start The start pointer would The last node doesn’t be saved in the private point to another node, so section of a data its pointer (called next) is structure class. set to NULL (indicated by slash). 18
  • 19. Linked Lists • The arrangement of nodes in the linked structure on the previous slide is often called a linked list. • We can access any element of the linked list, for retrieval of information. • We can also remove any element from the linked list (which would shorten the list). • We can also insert any element into any position in the linked list. 19
  • 20. Linked List Advantages … 5 3 7 2 1 … Removing an element from the middle of a linked list is fast. 20
  • 21. Linked List Advantages (cont.) … 5 3 2 1 … Removing an element from the middle of a linked list is fast. 21
  • 22. Removal Problem in Array 211 212 213 214 215 216 217 218 … 25 75 10 12 33 49 29 87 … Removing elements from the middle of an array (without leaving gaps) is more problematic. 22
  • 23. Removal Problem in Array (cont.) 211 212 213 214 215 216 217 218 … 25 75 10 33 49 29 87 … A loop must be used to slide each element on the right one slot to the left, one at a time… 23
  • 24. Removal Problem in Array (cont.) 211 212 213 214 215 216 217 218 … 25 75 10 33 49 29 87 … 211 212 213 214 215 216 217 218 … 25 75 10 33 49 29 87 … 211 212 213 214 215 216 217 218 … 25 75 10 33 49 29 87 … 24
  • 25. Removal Problem in Array (cont.) 211 212 213 214 215 216 217 218 … 25 75 10 33 49 29 87 … Only 100,000 more to go! 25
  • 26. Linked List Advantages (cont.) • Linked lists also waste less memory for large elements (records of information). • Wasted memory is memory space in the data structure not used for data. • In arrays, the wasted memory is the part of the array not being utilized. • In linked lists, the wasted memory is the pointer in each node. 26
  • 27. Linked List Advantages (cont.) start Linked List Array 27
  • 28. Accessing info start To access the info in the first node: (*start).info Or (better yet) dereference and member start->info access in one shot 28
  • 29. Accessing info (cont.) start To access the info in the second node: start->next->info 29
  • 30. Finding a Possible Mercedes start item maker: Mercedes price: Mercedes … year: operator == Let’s solve the problem, but let’s assume that item is passed in as a parameter (of type T). This is normally what would happen. Instead of the CarType struct having an overloaded != operator, it will have an overloaded == operator. 30
  • 31. Finding a Possible Mercedes (cont.) start item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) // overloaded == found = true; if ( !found ) ptr = ptr->next; 31 }
  • 32. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) // overloaded == found = true; if ( !found ) ptr = ptr->next; 32 }
  • 33. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) // overloaded == found = true; if ( !found ) ptr = ptr->next; } 33
  • 34. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) // overloaded == found = true; if ( !found ) ptr = ptr->next; } 34
  • 35. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) // overloaded == found = true; if ( !found ) ptr = ptr->next; } 35
  • 36. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) found = true; if ( !found ) ptr = ptr->next; } 36
  • 37. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) found = true; if ( !found ) ptr = ptr->next; } 37
  • 38. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) found = true; if ( !found ) ptr = ptr->next; } 38
  • 39. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) // overloaded == found = true; if ( !found ) ptr = ptr->next; } 39
  • 40. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) found = true; if ( !found ) ptr = ptr->next; 40 }
  • 41. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { After going through the if ( ptr->info == item ) loop several times… found = true; if ( !found ) ptr = ptr->next; } 41
  • 42. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { Notice that found is if ( ptr->info == item ) only set to true if ptr found = true; is not NULL and if ( !found ) Mercedes is found … ptr = ptr->next; 42 }
  • 43. Finding a Possible Mercedes (cont.) start ptr item maker: Mercedes price: Mercedes … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) then, !found is false found = true; and the loop exits if ( !found ) ptr = ptr->next; } 43
  • 44. What If Mercedes Does Not Exist? start ptr item maker: Mercedes price: … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; If Mercedes is not found, while (ptr != NULL && !found ) { if ( ptr->info == item ) ptr eventually gets set to found = true; NULL. if ( !found ) ptr = ptr->next; } 44
  • 45. What If Mercedes Does not Exist? (cont.) start ptr is set to NULL item maker: Mercedes price: … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; If Mercedes is not while (ptr != NULL && !found ) { if ( ptr->info == item ) found, ptr eventually found = true; gets set to NULL. if ( !found ) ptr = ptr->next; } 45
  • 46. What If Mercedes Does not Exist? (cont.) start ptr is set to NULL item maker: Mercedes price: … year: operator == CarType item; item.maker = "Mercedes"; found: false Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { Exit from loop if ( ptr->info == item ) because ptr is found = true; NULL. if ( !found ) ptr = ptr->next; } 46
  • 47. What If Finding in an Empty Linked List? • When a linked list is empty, the start pointer should always be set to NULL. • The start pointer would be set to NULL inside the constructor, when an empty linked list is first made. 47
  • 48. Finding in an Empty List item start is set to NULL maker: Mercedes price: year: operator == Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) found = true; SAME CODE if ( !found ) ptr = ptr->next; } 48
  • 49. Finding in an Empty List (cont.) item start is set to NULL maker: Mercedes ptr is set to NULL price: year: operator == Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { if ( ptr->info == item ) found = true; if ( !found ) ptr = ptr->next; } 49
  • 50. Finding in an Empty List (cont.) item start is set to NULL maker: Mercedes ptr is set to NULL price: year: operator == Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { found: false if ( ptr->info == item ) found = true; if ( !found ) ptr = ptr->next; } 50
  • 51. Finding in an Empty List (cont.) item start is set to NULL maker: Mercedes ptr is set to NULL price: year: operator == Node<T> *ptr = start; bool found = false; while (ptr != NULL && !found ) { found: false if ( ptr->info == item ) found = true; Exit loop if ( !found ) because ptr is ptr = ptr->next; NULL. } 51
  • 52. Inserting a New Node • Let’s assume that we want to insert a new node at the beginning of a linked list. • Assume that the client passes in a parameter called element (of type T). • We would like to place the element into a node and insert the node at the beginning of the linked list. 52
  • 53. Inserting a Node at Front element start All new nodes must be made in the heap, SO… 53
  • 54. Inserting a Node at Front (cont.) element start ptr Node<T> *ptr = new Node<T>; 54
  • 55. Inserting a Node at Front (cont.) element start ptr Node<T> *ptr = new Node<T>; Now we have to store element into the node 55
  • 56. Inserting a Node at Front (cont.) element start ptr Node<T> *ptr = new Node<T>; ptr->info = element; 56
  • 57. Inserting a Node at Front (cont.) element start Now we have to think about how to ptr make the pointer called “next” point to the first node in the list, to link it in Node<T> *ptr = new Node<T>; ptr->info = element; 57
  • 58. Inserting a Node at Front (cont.) element start You can’t successfully write code like ptr this without thinking about addresses. Node<T> *ptr = new Node<T>; ptr->info = element; 58
  • 59. Inserting a Node at Front (cont.) element start REMEMBER…when you want to ptr change the way a pointer points, you HAVE to assign a different address to it Node<T> *ptr = new Node<T>; ptr->info = element; 59
  • 60. Inserting a Node at Front (cont.) element start Right now, the pointer called “next” ptr doesn’t have a valid address assigned to it. Node<T> *ptr = new Node<T>; ptr->info = element; 60
  • 61. Inserting a Node at Front (cont.) element start To store the correct address in it, we ptr have to find the address of the first node of the linked list. Node<T> *ptr = new Node<T>; ptr->info = element; 61
  • 62. Inserting a Node at Front (cont.) element start ptr Where is the address of the first node stored? Node<T> *ptr = new Node<T>; ptr->info = element; 62
  • 63. Inserting a Node at Front (cont.) element start Now think, the address would be stored ptr in something that points to it. So where is it stored? Node<T> *ptr = new Node<T>; ptr->info = element; 63
  • 64. Inserting a Node at Front (cont.) element start ptr That’s right, in the start pointer. Node<T> *ptr = new Node<T>; ptr->info = element; 64
  • 65. Inserting a Node at Front (cont.) element start ptr So now, all we have to do is copy that address into the pointer called “next” Node<T> *ptr = new Node<T>; ptr->info = element; 65
  • 66. Inserting a Node at Front (cont.) element start ptr Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; 66
  • 67. Inserting a Node at Front (cont.) element start ptr Well, it’s been inserted. But start should point to the first node now. Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; 67
  • 68. Inserting a Node at Front (cont.) element start REMEMBER…when you want to ptr change the way a pointer points, you have to assign a different address to it Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; 68
  • 69. Inserting a Node at Front (cont.) element start We’d like start to point to the new ptr node, so what stores the address of the new node? Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; 69
  • 70. Inserting a Node at Front (cont.) element start That’s right, ptr. So now all we have ptr to do is assign the address stored in ptr to the start pointer. Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; 70
  • 71. Inserting a Node at Front (cont.) element start ptr Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; start = ptr; 71
  • 72. Inserting a Node at Front (cont.) element start ptr Easy, right? Node<T> *ptr = new Node<T>; ptr->info = element; ptr->next = start; start = ptr; 72
  • 73. REMEMBER… • Use drawings when working with linked lists, until you become an expert. • When you want to change the way a pointer points, you have to assign a different address to it. • You can find the address you need by looking at other pointers (remember that they store addresses). 73
  • 74. Inserting into the Middle of a Linked List • Suppose we know that there is a Mercedes in a linked list. • We would like to insert a node containing Honda right after it. • We first find the Mercedes, using code that we looked at before. 74
  • 75. Inserting a Node at Middle start ptr element maker: Mercedes price: Mercedes … year: operator != After this code executes, ptr points to the node that has Mercedes. Node<T> *ptr = start; while ( ptr->info != element ) // element is a parameter ptr = ptr->next; 75
  • 76. Inserting a Node at Middle (cont.) start ptr element maker: Mercedes price: Mercedes … year: operator != Now we would like to insert a CarType object called elementToInsert (containing Honda), which would also be passed in as a parameter, right after the Mercedes 76
  • 77. Inserting a Node at Middle (cont.) start ptr maker: Honda price: 5000 Mercedes … year: 1985 operator != elementToInsert Well, all new nodes are created in the heap, SO….. 77
  • 78. Inserting a Node at Middle (cont.) start ptr maker: Honda price: 5000 Mercedes … year: 1985 operator != newNode elementToInsert Node<T> *newNode = new Node<T>; 78
  • 79. Inserting a Node at Middle (cont.) start ptr maker: Honda price: 5000 Mercedes … year: 1985 operator != newNode elementToInsert Node<T> *newNode = new Node<T>; Now, how about placing elementToInsert into the new node? 79
  • 80. Inserting a Node at Middle (cont.) start ptr maker: Honda price: 5000 Mercedes … year: 1985 operator != newNode elementToInsert Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 80
  • 81. Inserting a Node at Middle (cont.) start ptr maker: Honda price: 5000 Mercedes … year: 1985 operator != newNode elementToInsert Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 81
  • 82. Inserting a Node at Middle (cont.) start ptr Now, what we want is Mercedes shown by the dashed … arrows; this would cause the insertion of the node newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 82
  • 83. Inserting a Node at Middle (cont.) start ptr We have two pointers we need to Mercedes … change – but we have to be careful about the way we change them newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 83
  • 84. Inserting a Node at Middle (cont.) start ptr If we change the left pointer first, Mercedes … we will no longer be able to access the last node (memory leak) newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 84
  • 85. Inserting a Node at Middle (cont.) start ptr So, we first have to assign the address Mercedes … of the last node into the “next” pointer of the new node newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 85
  • 86. Inserting a Node at Middle (cont.) start ptr Where is the Mercedes … address of the last node stored? newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 86
  • 87. Inserting a Node at Middle (cont.) start ptr That’s right, it is Mercedes … stored in ptr->next newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; 87
  • 88. Inserting a Node at Middle (cont.) start ptr Mercedes … newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; newNode->next = ptr->next; 88
  • 89. Inserting a Node at Middle (cont.) start ptr Mercedes Mercedes … newNode Node<T> *newNode = new Node<T>; newNode->info = elementToInsert; newNode->next = ptr->next; ptr->next = newNode; 89
  • 90. Removing a Node • Suppose we definitely know there is a Mercedes in the linked list and we wish to remove the node that contains it. • We need to find the node first. 90
  • 91. Removing the First Node start Mercedes … Mercedes is in the first node Node<T> *ptr = start; if ( ptr->info == element ) start = start->next; 91
  • 92. Removing the First Node (cont.) start Mercedes ptr … Node<T> *ptr = start; if ( ptr->info == element ) start = start->next; 92
  • 93. Removing the First Node (cont.) start Mercedes ptr … Node<T> *ptr = start; if ( ptr->info == element ) start = start->next; 93
  • 94. Removing the First Node (cont.) Mercedes ptr start … Node<T> *ptr = start; if ( ptr->info == element ) start = start->next; 94
  • 95. Removing the First Node (cont.) ptr start … Node<T> *ptr = start; Well, start points to the if ( ptr->info == element ) { beginning of the new start = start->next; linked list, but a node isn’t delete ptr; removed unless we free it. } 95
  • 96. Removing the First Node (cont.) ptr start … Node<T> *ptr = start; Now, let’s consider the if ( ptr->info == element ) { other case whereby start = start->next; Mercedes is in the delete ptr; middle of the list. } 96
  • 97. Removing a Middle Node start ptr Mercedes … else { The while loop while ( ptr->next->info != element ) points ptr to the ptr = ptr->next; node BEFORE the node that has Mercedes. 97
  • 98. Removing a Middle Node (cont.) start ptr Mercedes … else { while ( ptr->next->info != element ) We need to join the ptr = ptr->next; node before Mercedes to the node after Mercedes 98
  • 99. Removing a Middle Node (cont.) start ptr ptr2 Mercedes … else { while ( ptr->next->info != element ) But we mus keep ptr = ptr->next; a pointer to the node that has Node<T> *ptr2 = ptr->next; Mercedes 99
  • 100. Removing a Middle Node (cont.) start ptr ptr2 Mercedes … else { while ( ptr->next->info != element ) ptr = ptr->next; We now join the node before Node<T> *ptr2 = ptr->next; Mercedes to the ptr->next = ptr2->next; node after Mercedes 100
  • 101. Removing a Middle Node (cont.) start ptr ptr2 … else { while ( ptr->next->info != element ) ptr = ptr->next; We then delete the Node<T> *ptr2 = ptr->next; ptr->next = ptr2->next; node that has Mercedes delete ptr2; We did it! 101
  • 102. What If Mercedes is the Last Node? • Would our code still work? • Try to consider every possible situation in code design. 102
  • 103. Removing the Last Node start ptr Mercedes … else { while ( ptr->next->info != element ) After looping, ptr ptr = ptr->next; stops on the next-to-the-last Node<T> *ptr2 = ptr->next; node ptr->next = ptr2->next; delete ptr2; } 103
  • 104. Removing the Last Node (cont.) start ptr ptr2 Mercedes … else { while ( ptr->next->info != element ) ptr = ptr->next; Node<T> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; } 104
  • 105. Removing the Last Node (cont.) start ptr ptr2 Mercedes … else { while ( ptr->next->info != element ) ptr = ptr->next; Node<T> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; } 105
  • 106. Removing the Last Node (cont.) start ptr ptr2 … else { while ( ptr->next->info != element ) The code works ptr = ptr->next; in removing the Node<T> *ptr2 = ptr->next; last node. ptr->next = ptr2->next; delete ptr2; } 106
  • 107. Working With Linked Lists • As you can see, sometimes you have to do a lot of thinking and problem-solving when working with linked lists. • It is not always obvious how to write code. • You can’t memorize the code, because it will not quite fit situations that you will encounter. • It is a matter of using logic (and knowing a few tricks of the trade). 107
  • 108. Code for Removing a Node 1 Node<T> *ptr = start; Here is the resulting 2 if ( ptr->info == element ) { code for removing a 3 start = start->next; node. It is assumes 4 delete ptr; the node we are 5 } looking for is in the 6 else { linked list. 7 while ( ptr->next->info != element ) 8 ptr = ptr->next; 9 Node<T> *ptr2 = ptr->next; 10 ptr->next = ptr2->next; 11 delete ptr2; 12 } 108
  • 109. Speed • In some situations, an array can be faster than a linked list, such as when a calculated index is used to access an element. • In other situations, a linked list can be faster than an array, such as when removing an element from the middle (as we saw before). – we usually need to search for the element to remove, but we search for it in both the array and linked list. 109
  • 110. Reference • Childs, J. S. (2008). Methods for Making Data Structures. C++ Classes and Data Structures. Prentice Hall. 110