You are on page 1of 10

CS301 Data Structures

Lecture No.
05
___________________________________________________________________

Data Structures
Lecture No. 05
Reading Material
Data Structures and Algorithm Analysis in C++

Chapter. 3
3.1, 3.2.5, 3.3.1, 3.3.2
(array implementation)

Summary
1)
2)
3)
4)

Benefits of using circular list


Abstract Data Type
Stacks
Stack Implementation using arrays

In the previous lecture, we demonstrated the use of the circular list for the resolution
of the Josephus problem. After writing a program with the help of this data structure, a
leader among ten persons was selected. You must have noted many things while trying
to solve the problem. These things will help us to understand the usage of data
structures in C++, thus making the programming easy. The code of the program is
given below.
#include "CList.cpp"
void main(int argc, char *argv[])
{
CList list;
int i, N=10, M=3;
for(i=1; i <= N; i++ ) list.add(i);
list.start();
while( list.length() > 1 ) {
for(i=1; i <= M; i++ ) list.next();
cout << "remove: " << list.get() << endl;
list.remove();
}
cout << "leader is: " << list.get() << endl;
}
In the program, we include the file of the class CList and create its object i.e. list. Then
we solve the problem by using the add, start, length, next, remove and get methods of
the class CList.
In the program, we have included already-defined data structure CList. After defining
its different methods, we have an interface of Clist. There is no need to be worry about
the nature of the list i.e. whether it is linked list, doubly linked list or an array. For us, it
Page 1 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
is only a list to be manipulated according to our requirement. You will see that a
programmer may use different methods of the list object to solve the problem. We add
elements to the list by a simple call of add method and go to the first element of the list
by start method. Here, the length method is used in the condition of the while loop.
Then we remove elements from the list and use the next, get and remove methods
during this process. We get the current element by using the get method, then remove
it by calling the remove method and then go to the next element by the method next.
This way, all the elements are removed from the list except one element, called the
leader. This one element remains there as we execute the while loop one less than the
length of the list.
In singly linked list, the next returns false when it reaches to the last node due to the
fact that the next field of the last node is set to NULL. But in a circularly linked list
there is no NULL. It will be there only when there is no node in the list.
The whole process, which we carried out to solve the Josephus problem, can also be
carried out with functions in C++. While adopting this way (of writing functions), we
have to write these functions whenever we write another program that manipulates a
list. In this method, we define a class of the data structure list and its different methods
for the purpose of manipulation. This way, this class, obviously its methods too, can be
used in any program where the manipulation of a list is needed. Thus there is reusability of the code. In a class, we encapsulate the data and its methods. This shows
that we are no longer interested in the internal process of the class. Rather, we simply
use it wherever needed. The circular linked list, earlier used for the resolution of the
Josephus problem, can also be employed in other problems. We have a class CList of
this circular linked list through which any number of objects of data type of circular
linked list can be created. Thus we can assume the class CList as a factory, creating as
many objects of list as needed. This class and its objects in any program can be used to
solve the problems with the help of its interface. The interface of this class consists of
some methods like add, remove, next, back, get and some other simple ones. While
carrying out programming, we will see that these classes (objects) help us very much
to solve different problems.

Benefits of using circular list


While solving the Josephus problem, it was witnessed that the usage of circular linked
list helped us make the solution trivial. We had to just write a code of some lines that
solved the whole problem. In the program, we included the class CList (which is of our
data structure i.e. circular linked list) and used all of its methods according to the
requirements. There was no problem regarding the working of the methods. We just
called these methods and their definition in the class CList worked well.
Now we will see what happens if we solve the Josephus problem by using an array
instead of the class in our program. In this case, we have to define an array and write
code to move back and forth in the array and to remove different elements properly in
a particular order. A programmer needs to be very careful while doing this, to reach the
solution of the problem. Thus our code becomes very complex and difficult for
someone to understand and modify it. Moreover we cannot use this code in some other
problem. Note that here we are talking about the use of an array in the main program,
not in the class that defines the CList data structure. There is no need to be worried
whether an array, singly linked list, doubly linked list is used or circular linked list being

Page 2 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
employed internally in implementing the list in defining the class of list data type. We
only want that it should create objects of list. The usage of the class of a data structure
simplifies the code of the program. We can also use this class wherever needed in other
programs. This shows that the choice of appropriate data structures can simplify an
algorithm. It can make the algorithm much faster and efficient.
In this course, we will see that there are different data structures, which makes the
algorithms very easy to solve our problems. Later, we will see how some elegant data
structures lie at the heart of major algorithms. There is also a course dedicated to study
different algorithms and recipes that can be used to solve host of complex problems.
Moreover, we will study different data structures in detail and see that with the use of a
proper data structure, we can solve a problem efficiently. A properly constructed data
structure will always help in the solution of problems.

Abstract Data Type


A data type is a collection of values and a set of operations on those values. That
collection and these operations form a mathematical construct that may be
implemented with the use of a particular hardware or software data structure. The term
abstract data type (ADT) refers to the basic mathematical concept that defines the data
type. We have discussed four different implementations of the list data structure. In
case of implementation of the list with the use of an array, the size of the array gives
difficulty if increased. To avoid this, we allocate memory dynamically for nodes before
connecting these nodes with the help of pointers. For this purpose, we made a singly
linked list and connected it with the next pointer to make a chain. Moving forward is
easy but going back is a difficult task. To overcome this problem, we made a doubly
linked list using prev and next pointers. With the help of these pointers, we can move
forward and backward very easily. Now we face another problem that the prev pointer
of first node and the next pointer of the last node are NULL. Therefore, we have to be
careful in case of NULL pointers. To remove the NULL pointers, we made the circular
link list by connecting the first and last node.
The program employing the list data structure is not concerned with its
implementation. We do not care how the list is being implemented whether through an
array, singly linked list, doubly linked list or circular linked list. It has been witnessed
that in these four implementations of the list, the interface remained the same i.e. it
implements the same methods like add, get, next, start and remove etc. This proves
that with this encapsulation attained by making a class, we are not concerned with its
internal implementation. The implementation of these abstract data types can be
changed anytime. These abstract data types are implemented using classes in C++. If
the list is implemented using arrays while not fulfilling the requirements, we can change
the list implementation. It can be implemented with the use of singly-link list or doubly
link list. As long as the interface is same, a programmer can change the internal
implementation of the list and the program using this list will not be affected at all. This
is the abstract data type (ADT). What we care about is the methods that are available
for use, with the List ADT i.e. add, get, and remove etc methods. We have not studied
enough examples to understand all the benefits of abstract data types. We will follow
this theme while developing other ADT. We will publish the interface and keep the
freedom to change the implementation of ADT without effecting users of the ADT. The
C++ classes provide a programmer an ability to create such ADTs. What benefits can
we get with the help of these ADTs and classes? When we develop an ADT or a class
or factory then the users of this factory are independent of how this factory works

Page 3 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
internally. Suppose that we have ordered the car factory (car class) to produce a new
car and it replies after a long time. If we ordered the remove method to remove one
node and we are waiting and it keeps on working and working. Then we might think
that its implementation is not correct. Although, we are not concerned with the internal
implementation of this ADT yet it is necessary to see whether this ADT is useful for
solving our problem or not. It should not become a bottleneck for us. If the method we
are using is too much time consuming or it has some problem in terms of algorithm
used. On one side, we only use the interfaces provided by these ADTs, classes, or
factories as long as they do what they promise. We are not concerned with the internal
details. On the other hand, we have to be careful that these factories or methods should
not take too much time so that these will not be useful for the problem.
This distinction will always be there. Sometimes, the source code of classes is not
provided. We will be provided libraries, as standard libraries are available with the
compiler. These classes are in compiled form i.e. are in object form or in binary form.
On opening these files, you will not see the C++ code, rather binary code. When you
read the assembly language code, it will give some idea what this binary code is about.
You can view the interface methods in the .h file. As an application programmer, you
have to see that the ADTs being used are written in a better way. The point to be
remembered here is that you should not worry about the internal implementation of
these ADTs. If we want to change the internal implementation of the ADTs, it can be
done without affecting the users of these ADTs. While writing a program, you should
check its performance. If at some point, you feel that it is slow, check the ADTs used at
that point. If some ADT is not working properly, you can ask the writer of the ADT to
change the internal implementation of that ADT to ensure that it works properly.

Stacks
Lets talk about another important data structure. You must have a fair idea of stacks.
Some examples of stacks in real life are stack of books, stack of plates etc. We can add
new items at the top of the stack or remove them from the top. We can only access the
elements of the stack at the top. Following is the definition of stacks.
Stack is a collection of elements arranged in a linear order
Lets see an example to understand this. Suppose we have some video cassettes. We
took one cassette and put it on the table. We get another cassette and put it on the top
of first cassette. Now there are two cassettes on the table- one at the top of other.
Now we take the third cassette and stack it on the two. Take the fourth cassette and
stack it on the three cassettes.
Now if we want to take the cassette, we can get the fourth cassette which is at the top
and remove it from the stack. Now we can remove the third cassette from the stack
and so on. Suppose that we have fifty cassettes stacked on each other and want to
access the first cassette that is at the bottom of the stack. What will happen? All the
cassettes will fell down. It will not happen exactly the same in the computer. There may
be some problem. It does not mean that our data structure is incorrect. As we see in
the above example that the top most cassette will be removed first and the new
cassette will be stacked at the top. The same example can be repeated with the books.
In the daily life, we deal with the stacked goods very carefully.

Page 4 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
Now we will discuss how to create a stack data structure or a factory, going to create
stack object for us. What will be the attributes of this object? During the discussion on
the list, we came to know that a programmer adds values in the list, removes values
from the list and moves forward and backward. In case of a stack too, we want to add
things and remove things. We will not move forward or backward in the stack. New
items can be added or removed at the top only. We can not suggest the removal of the
middle element of the stack.
Lets talk about the interface methods of the stacks. Some important methods are:
Method Name
push(x)
pop()
top()

Description
Insert x as the top element of the stack
Remove the top element of the stack and return it.
Return the top element without removing it from the stack.

The push(x) method will take an element and insert it at the top of the stack. This
element will become top element. The pop() method will remove the top element of the
stock and return it to the calling program. The top() method returns the top-most stack
element but does not remove it from the stack. The interface method names that we
choose has special objective. In case of list, we have used add, remove, get, set as the
suitable names. However, for stack, we are using push, pop and top. We can depict the
activity from the method name like push means that we are placing an element on the
top of the stack and pushing the other elements down.
The example of a hotels kitchen may help understand the concept of stacks in a
comprehensive manner. In the kitchen, the plates are stacked in a cylinder having a
spring on the bottom. When a waiter picks a plate, the spring moves up the other
plates. This is a stack of plates. You will feel that you are pushing the plates in the
cylinder and when you take a plate from the cylinder it pops the other plates. The top
method is used to get the top- most element without removing it.
When you create classes, interfaces and methods, choose such names which depicts
what these method are doing. These names should be suitable for that class or factory.
Lets discuss the working of stack with the help of a diagram.

Page 5 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________

top
top
5

7
5

7
5

push(2)

push(5)

push(7)

push(1)

top
top

top
top

21

7
5

7
5

pop()

top

push(21)

7
5

top

2
21

2
pop()

top
pop()

2
5

pop()

At the start, the stack is empty. First of all, we push the value 2 in the stack. As a
result, the number 2 is placed in the stack. We have a top pointer that points at the top
element. Then we said push(5). Now see how 2 and 5 are stacked. The number 5 is
placed at the top of number 2 and the pointer top moves one step upward. Then we
pushed the number 7 which is placed on the top and the number 2 and 5 are below.
Similarly, we push number 1. The last figure in the first row shows the stacked values
of the numbers- 1, 7, 5 and 2.
Lets pop the elements from the stack. The first figure of second row shows the pop
operation. As a result, the number 1 is popped. Than again we push the number 21 on
the stack. The number 7, 5, and 2 are already in the stack and number 21 is pushed at
the top. If we pop now, the number 21 is popped. Now number 7 is at the top. If we
pop again, the number 7 is popped. Pop again and the number 5 is popped and number
2 remains in the stack. Here with the help of this diagram, we are proving that the
values are added at the top and removed at the top in a stack.
The last element to go into the stack is the first to come out. That is why, a stack is
known as LIFO (Last In First Out) structure. We know that the last element pushed in
the stack is at the top which is removed when we call pop. Lets see some other
scenarios. What happens if we call pop() while there is no element? One possible wayout is that we have isEmpty() function that returns true if stack is empty and false
otherwise. This is a boolean function that returns false if there is no element in the
stack. Otherwise, it will return true. The second option is this that when we call pop on
an empty stack, it throws an exception. This is a concept of advanced C++. Exception
is also a way to convey that some unusual condition has arisen or something has gone
wrong. Suppose, if we have a division method and try to divide some number with
zero. This method will throw division by zero exception. Currently we will not throw
an exception but use the isEmpty() method. The user who is employing the stack is
Page 6 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
responsible to call the isEmpty() method before calling the pop. Call the pop method if
isEmpty() returns false . Otherwise, there will be a problem.

Stack Implementation using array


Lets discuss the implementation of the stack. Suppose we implement the stack using
the arrays. The stack shown in the above diagram may be considered as an array. Here
the array is shown vertically. We can implement the stack using array. The interface will
remain as push and pop methods. The user of the stack does not need to know that the
stack is internally implemented with the help of array. The worst case for insertion and
deletion from an array may happen when we insert and delete from the beginning of
the array. We have to shift elements to the right for insertion and left for removal of an
element. We face the same problem while implementing the list with the use of the
array. If we push and pop the elements from the start of the array for stack
implementation, this problem will arise. In case of push, we have to shift the stack
elements to the right. However, in case of pop, after removing the element, we have to
shift the elements of stack that are in the array to the left. If we push the element at the
end of the array, there is no need to shift any element. Similarly as the pop method
removes the last element of the stack which is at the end of the array, no element is
shifted. To insert and remove elements at the end of the array we need not to shift its
elements. Best case for insert and delete is at the end of the array where there is no
need to shift any element. We should implement push() and pop() by inserting and
deleting at the end of an array.

top

7
5
2

top = 3

In the above diagram, on the left side we have a stack. There are four elements in the
stack i.e. 1, 7, 5 and 2. The element 1 is the extreme-most that means that it is inserted
in the end whereas 7, 5, and 2 have been added before. As this is a LIFO structure so
the element 1 should be popped first. On the right side we have an array with positions
0, 1, 2, 3 and so on. We have inserted the numbers 2, 5, 7 and 1. We have decided that
the elements should be inserted at the end of the array. Therefore the most recent
element i.e. 1 is at position 3. The top is the index representing the position of the most
recent element. Now we will discuss the stack implementation in detail using array.
We have to choose a maximum size for the array. It is possible that the array may fillup if we push enough elements. Now more elements cannot be pushed. Now what
should the user of the stack do? Internally, we have implemented the stack using array
which can be full. To avoid this, we write isFull() method that will return a boolean
value. If this method returns true, it means that the stack (array) is full and no more
elements can be inserted. Therefore before calling the push(x), the user should call
isFull() method. If isFull() returns false, it will depict that stack is not full and an
element can be inserted. This method has become the part of the stack interface. So we
Page 7 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
have two more methods in our interface i.e. isEmpty() and isFull().
Now we will discuss the actual C++ code of these operations. These methods are part
of stack class or stack factory. We have an array named A while current is its index.
The code of pop() method is as:
int pop()
{
return A[current--];
}
In this method, the recent element is returned to the caller, reducing the size of the
array by 1.
The code of push method is:
void push(int x)
{
A[++current] = x;
}
We know that ++current means that add one to the current and then use it. That also
shows that element x should be inserted at current plus one position. Here we are not
testing that this current index has increased from the array size or not. As discussed
earlier that before using the push method, the user must call isFull() method. Similarly
it is the responsibility of the user to call the isEmpty() method before calling the pop
method. Therefore there is no if statement in the push and pop method.
The code of the top() method is:
int top()
{
return A[current];
}
This method returns the element at the current position. We are not changing the value
of current here. We simply want to return the top element.
int isEmpty()
{
return ( current == -1 );
}
This method also tests the value of the current whether it is equal to -1 or not. Initially
when the stack is created, the value of current will be -1. If the user calls the isEmpty()
method before pushing any element, it will return true.
int isFull()
{
return ( current == size-1);
}

Page 8 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
This method checks that the stack is full or not. The variable size shows the size of the
array. If the current is equal to the size minus one, it means that the stack is full and we
cannot insert any element in it.
We have determined the cost and benefit of all the data structures. Now we will see
how much time these methods take. A quick examination shows that all the five
operations take constant time. In case of list, the find method takes too much time as it
has to traverse the list. Whereas the add and remove methods are relatively quick. The
methods of stack are very simple. There is no complexity involved. We insert element
at one side and also remove from that side not in the middle or some other place.
Therefore we need not to carry out a lot of work. During the usage of the array, the
stack methods push, pop, top, isFull and isEmpty all are constant time operations.
There is not much difference of time between them.
The complete code of the program is:
/* Stack implementation using array */
#include <iostream.h>
/* The Stack class */
class Stack
{
public:
Stack() { size = 10; current = -1;} //constructor
int pop(){ return A[current--];}
// The pop function
void push(int x){A[++current] = x;} // The push function
int top(){ return A[current];}
// The top function
int isEmpty(){return ( current == -1 );} // Will return true when stack is empty
int isFull(){ return ( current == size-1);} // Will return true when stack is full
private:
int object;
int current;
int size;
int A[10];

// The data element


// Index of the array
// max size of the array
// Array of 10 elements

};
// The main method
int main()
{
Stack stack;
// creating a stack object
// pushing the 10 elements to the stack
for(int i = 0; i < 12; i++)
{
if(!stack.isFull())
// checking stack is full or not
stack.push(i);
// push the element at the top
else
cout <<"\n Stack is full, can't insert new element";
}
Page 9 of 10

CS301 Data Structures


Lecture No.
05
___________________________________________________________________
// pop the elements at the stack
for (int i = 0; i < 12; i++)
{
if(!stack.isEmpty())
// checking stack is empty or not
cout << "\n The popped element = " << stack.pop();
else
cout <<"\n Stack is empty, can't pop";
}
}
The output of the program is:
Stack is full, can't insert new element
Stack is full, can't insert new element
The popped element = 9
The popped element = 8
The popped element = 7
The popped element = 6
The popped element = 5
The popped element = 4
The popped element = 3
The popped element = 2
The popped element = 1
The popped element = 0
Stack is empty, can't pop
Stack is empty, can't pop
However, a programmer finds the size-related problems in case of an array. What
should we do when the array is full? We can avoid the size limitation of a stack
implemented with an array by using a linked list to hold the stack elements. Further
discussion on this issue will be made in the next lecture.

Page 10 of 10

You might also like