4.1 Pointers and a LinkedListA Linked List isa sequence of zero or more elements called nodes each

containing two kinds of information: some data and one or more links called pointers to other

Key Terms ? Overflow: Running out of space. ? Pointer: An object, often a variable, that stores the location (that is the machine address) of some other object, typically of a structure containing data that we wish to manipulate. (Also sometimes called a link or a reference) ? Linked list: A list in which each entry contains a pointer giving the location of the next entry.

? Contiguous: Next to each other, touching, adjoining; used in contrast to linked. ? Automatic object: An object that exists as long as the block of program declaring it is active; referenced by giving it a name when writing the program. ? Dynamic object: An object that is created (and perhaps destroyed) while the program is running; accessed indirectly via pointers.

Pointers in C++ ? Notation: C++ uses an asterisk * to denote a pointer. If Item is a type, then a pointer to such an Item object has the type Item *. For example, Item *item ptr; declares item ptr as a pointer variable to an Item object. ? Creating dynamic objects: item_ptr = new Item; creates a new

The dynamic objects that we create are kept in an area of computer memory called the free store (or the heap). ? Deleting dynamic objects: delete item_ptr; disposes of the dynamic object to which item_ptr points and returns the space it occupies to the free store so it can be used again. After this delete statement is executed, the pointer variable item_ptr is undefined and so should not be used until it is assigned a new value.

? Following pointers: *item_ptr denotes the object to which item_ptr points. The action of taking “ *item_ptr is called *referencing the pointer *item_ptr.” ? NULL pointers : If a pointer variable item_ptr has no dynamic object to which it currently refers, then it should be given the special value item_ptr = NULL;

In diagrams we reserve the electrical ground symbol

for NULL pointers. The value NULL is used as a constant for all pointer types and is generic in that the same value can be assigned to a variable of any pointer type.

? Undefined pointers versus NULL pointers := NULL means that item_ptr currently item_ptrpoints to no dynamic object. If the value of item_ptr is undefined, then item_ptr might point to any random location in memory.

The value of p + i gives the memory address offset from p by i Item objects. That is, the expression p+i actually yields the address p+n? i, where n is the number of bytes of storage occupied by a simple object of type Item.

? Addresses of automatic objects: If x is a variable of type Item, then &x is a value of type Item* that gives the address of x. In this case, a declaration and assignment such as Item *ptr = &x would establish a pointer, ptr, to the object x. ? Address of an array: The address of the initial element of an array is found by using the array's name without any attached [ ] operators. For example, given a declaration Item x[20] the assignment Item *ptr = x

sets up a pointer ptr to the initial element of the array x. Observe that an assignment expression ptr = &(x[0]) could also be used to nd this address. ? Pointers to structures: If p is a pointer to a structure object that has a data member called the data, then we could access this data member with the expression (*p).the data, but C++ provides the operator -> as a shorthand, so we can replace the expression (*p).the data by the equivalent, but more convenient,

The Basics of Linked Structures A linked structure is made up of nodes, each containing both the information that is to be stored as an entry of the structure and a pointer telling where to find the next node in the structure. We shall refer to these nodes making up a linked structure as the nodes of the structure, and the pointers we often call links. Since the link in each node tells where to nd the next node of the structure, we shall

encapsulation: If we do not use aclass to contain our stack, we lose the ability to set up methods for the stack.

?Maintain the logical distinction between the stack itself, made up of all of its entries (each in a node), and the top of the stack,which is a pointer to a single node. ?Maintain consistency with other data

4.3 Linked Stacks with SafeguardsClient code can apply the methods of linked stacks in ways that lead to the accumulation of garbage or that break the encapsulation of Stack objects. C++ provides three devices (additional class methods) to alleviate these problems: ?destructors

?copy constructors ?overloaded assignment operators These new methods replace compiler generated default behavior and are often called silently (that is, without explicit action by a client).

Suppose that the linked Stack implementation is used. As soon as the object small goes out of scope, the data stored in small becomes garbage. Over the course of a million iterations of the loop, a lot of garbage will accumulate. The loop would have executed without any problem with a contiguous Stack implementation, where all allocated space for member data is released every time a Stack object goes out of scope.

The Destructor Definition:A destructor is a special method in a class that is automatically executed on objects of the class immediately before they go out of scope. The client does not need to call a destructor explicitly and does not even need to know it is present. Destructors are often used to delete dynamically allocated objects that would otherwise become garbage.

Declaration:The destructor must be declared as a class method without return type and without parameters. Its name is given by adding a ~ prefix to the corresponding class name. Hence, the prototype for a Stack destructor is: Stack :: ~Stack( );

Stack :: ~Stack( ) // Destructor // Post: The Stack is cleared. { while (!empty( )) pop( ); }Policy Every linked structure should be equipped with a destructor to clear its objects before they go out of scope.

Misbehaviors: ?Lost data space. ?Two stacks have shared nodes. ?The destructor on inner_stack deletes outer_stack. ?Such a deletion leaves the pointer outer_stack.top Assignment Overloading the node addressing what a random memory In C++, Operator we implement special methods, location. overloaded assignment operators to known asredefine the effect of assignment. Whenever the C++ compiler translates an assignment expression of the form x = y, it first checks whether the class of x has an overloaded

Prototype:void Stack :: operator = (const Stack &original); This declares a Stack method called operator = , the overloaded assignment operator, that can be invoked with x.operator = (y); or x = y; By looking at the type(s) of its operands, the C++ compiler can tell that it should use the overloaded operator rather than the usual Implementation outline: assignment.

? Make a copy of the data stacked in the calling parameter. ? Clear out any data already in the Stack object being assigned to.

In this code, a copy of the Stack vital data is passed to the function. The Stack copy shares its nodes with the Stack vital_data, and therefore when a Stack destructor is applied to copy, at the end of the function, vital_data is also destroyed.

Solution:If we include a copy constructor as a member of our Stack class, our copy constructor will be invoked whenever the compiler needs to copy Stack objects. We can thus ensure that Stack objects are copied using value semantics. For any class, a standard way to declare a copy constructor is as a constructor with one argument that is declared as a constant reference to an object of the class. Hence, a Stack copy constructor would normally have the following prototype: Stack :: Stack(const Stack &original);

Implementation outline:? Deal with the case of copying an empty Stack. ? Copy the first node. ? Run a loop to copy all of the other nodes. Linked-stack copy constructor:Stack :: Stack(const Stack &original) // copy constructor /* Post: The Stack is initialized as a copy of Stack original . */

4.5 Application : Polynomials Arithmetic a program that simulates a ?We developcalculator that does addition, subtraction, multiplication, division, and other operations for polynomials rather than numbers. ?We model a reverse Polish calculator whose operands (polynomials) are entered before the

Performing Commandsbool do_command(char command, Stack &stored_polynomials) /* Pre: The rst parameter species a valid calculator command. Post: The command specied by the rst parameter has been applied to the Stack of Polynomial objects given by the second parameter. A result of true is returned unless command == ?q? . Uses: The classes Stack and Polynomial . */ { Polynomial p, q, r; switch (command)

and utility packages are properly integrated Data Structures for into the program. Polynomials

1. Each node represents one term of a polynomial and is a structure containing a coefficient, an exponent, and every polynomial are stored in the 2. The terms of a pointer to the next term of the order

polynomial. of decreasing exponent within the linked queue,and 3. Terms with zero have the same exponent. the coefficient are not stored in no two terms polynomial.4. The polyno

4.6 Abstract Data Types and ImplementationsDEFINITION A stack of elements of type T is a finite sequenc

e of elements of T together with the following operations: 1. Create the stack, leaving it empty. 2. Test whether the stack is Empty. 3. Push a new entry onto the top of the stack, provided the stack is not full. 4. Pop the entry off the top of the stack, provided the stack is not empty.

Abstract QueueDEFINITION A queue of elements of type T is a finite sequence of elements of T together with the following operations: 1. Create the queue, leaving it empty. 2. Test whether the queue is Empty. 3. Append a new entry onto the rear of the queue, provided the queue is not full. 4. Serve (and remove) the entry from the front of the queue, provided the queue is not empty.

extended queueDEFINITION An extended queue of elements of type T is a queue of elements of T together with the following

additional operations:4. Determine whether the queue is full or not. 5. Find the size of the queue. 6. Serve and retrieve the front entry in the queue, provided

the queue is not empty.7. Clear the queue to make it empty.

Pointers and Pitfalls◆Before choosing implementations, be sure that all the data structures and their associated operations are fully specified on the abstract level. ◆To help in the choice between linked and contiguous implementations,consider the necessary operations on the data structure. Linked structures are more flexible in regard to insertions, deletions, and rearrangement; contiguous structures are sometimes faster. ◆Contiguous structures usually require less computer memory,computer time, and programming effort when the items in the structure are small and the algorithms are simple.

◆Dynamic memory and pointers allow a program to adapt automatically to a wide range of application sizes and provide flexibility in space allocation among different data structures. Automatic memory is sometimes more efficient for applications whose size can be completely specified in advance. ◆Before reassigning a pointer, make sure that the object that it references will not become garbage. ◆Set uninitialized pointers to NULL. ◆Linked data structures should be implemented with destructors,copy constructors, and overloaded assignment operators.

◆Draw ì before?and ì after?diagrams of the appropriate part of a linked structure, showing the relevant pointers and the way in which they should be changed. If they might help, also draw diagrams showing intermediate stages of the process. ◆To determine in what order values should be placed in the pointer fields to carry out the various changes, it is usually better first to assign the values to previously undefined pointers,then to those with value NULL, and finally to the remaining pointers. After one pointer variable has been copied to another, the first is free to be reassigned

◆Be sure that no links are left undened at the conclusion of a method of a linked structure, either as links in new nodes that have never been assigned or links in old nodes that have become dangling,

that is, that point to nodes that no longer are used. Such links should either be reassigned to nodes still in use or set to the value NULL. ◆Verify that your algorithm works correctly for an empty structure and for a structure with only one node.

◆Avoid the use of constructions such as (p->next)->next, even though they are syntactically correct. A single object should involve only a single pointer dereferencing. Constructions with repeated dereferencing usually indicate that the algorithms can be improved by rethinking what pointer variables should be declared in the algorithm, introducing