Data Structures Course Overview 2017-2018
Data Structures Course Overview 2017-2018
Technology
Data Structures
Course objectives
This course aims to make the student capable of understanding and writing
different data structures as:
▪ Array
▪ String
▪ Linked List
▪ Stack
▪ Queue
Introduction
In computer science, a data structure is a particular way of organizing and storing
data in a computer so that it can be accessed and modified efficiently.
More precisely, a data structure is a collection of data values, the relationships
among them, and the functions or operations that can be applied to the data.
The data structures can also be classified on the basis of the following
characteristics:
Characteristic Description
Static Static data structures are those whose sizes and structures
associated memory locations are fixed, at compile time.
Example: Array
Classification according to structure :In these data structures the elements form a
sequence, or the elements do not form a sequence.
Data Structures Academic Year 2017-2018
Dynamic memory allocation is the ability for a program to obtain more memory
space at execution time to hold new nodes and to release space no longer needed.
Example: Linked Lists, Stacks, Queues and Trees
The data structures can be viewed in two ways, physically and logically.
▪ The physical data structure refers to the physical arrangement of the data on
the memory.
▪ The logical data structure concerns how the data "seem" to be arranged and
the meanings of the data elements in relation to one another.
Data Structures Academic Year 2017-2018
Physical structure for one-dimensional array with five elements will appear in
memory as shown below:
We can find out the location of any element by using following formula:
Loc (ArrayName [k]) = Loc (ArrayName [1]) + (k-LB)* w
where:
Loc (ArrayName [k]): is the address of the kth element of ArrayName.
Loc (ArrayName [1]): is the base address or address of first element of ArrayName.
w : is the number of bytes taken by one element(element size).
LB : is the lower bound.
Example1 : Suppose we want to find out Loc (A [3]) that store as the following figure
in two case (LB=1 and LB=0), for it, we have: Base(A)=1000, w = 2 bytes.
LB=0 LB=1
in Case LB = 1 If Case LB = 0
LOC(A[3])=1000 + 2 (3 – 1) LOC(A[3])=1000 + 2 *3
= 1000 + 2 (2) = 1000 + 6
= 1000 + 4 = 1006
= 1004
In the computer memory, all elements are stored linearly using contiguous
addresses. Therefore, in order to store a two-dimensional matrix, two dimensional
address space must be mapped to one-dimensional address space. There two
methods for arranging two or multidimensional :
1. Row-major order
2. Column-major order
For example the physical structure for array with 3X3 elements will appear in
memory as shown below in two methods:
In row-major order:
o consecutive elements of the rows of the array are contiguous in memory.
o Used in C, C++, PL/I, Pascal, Python and Java.
Data Structures Academic Year 2017-2018
▪ in column-major order:
o consecutive elements of the columns are contiguous.
o Used in Fortran, OpenGL and Matlab.
We can find out the location of any element in array (NXM) by using following
formulas:
Loc(A[[i,j]) : is the location of the element in the ith row and jth column.
Loc (A [1,1]) : is the base address or address of the first element of the array A.
w : is the number of bytes required to store single element of the array A.
M : is the total number of columns in the array.
Address Elements
1000 10
20 LOC (A [3,2]) = 1000 + 2 [4 (3-1) + (2-1)]
1002
50 = 1000 + 2 [4 (2) + 1]
1004
60 = 1000 + 2 [8 + 1]
1006
90 = 1000 + 2 [9]
1008
= 1000 + 18
1010 40
= 1018
1012 30
1014 80
1016 75
1018 55
1020 65
1022 79
1000 10
1002 90 LOC (A [3,2]) = 1000 + 2 [3 (2-1) + (3-1)]
1004 75 = 1000 + 2 [3 (1) + 2]
1006 20 = 1000 + 2 [3 + 2]
1008 40 = 1000 + 2 [5]
1010 = 1000 + 10
55
1012 = 1010
50
1014 30
1016 65
1018 60
1020 80
1022
79
Data Structures Academic Year 2017-2018
H.W.
1. You have the matrix A [3, 4] and the base address is 1500. By using rows major order:
a. Draw logical structure and physical structure of the matrix A.
b. find the address of the element A [2, 3].
2. You have the matrix B [5, 6] and the base address is 500. By using two method of arrange
matrix in memory:
a. Draw logical structure and physical structure of the matrix B.
b. find the address of the element B [2, 3].
In case three Dimensional Arrays, memory-address of the element A[i,j,K] with dimension
(NXMXR) is given by:
where:
R : number of levels
N: number of rows
M: number of column
Example : Suppose A3 x 3 X 3(N=3, M=3 and R=3) integer array A and base address =1000 and
number of bytes(w)=2. find the location of A [3,2,2] by using two method of arrange matrix
in memory:
1. Row order
Physical structure Logical structure
Data Structures Academic Year 2017-2018
Loc(A[3,2,2])= 1000+2(3*3*(2-1)+3*(3-1)+2-1)
= 1000 + 2(9+6+1)
= 1032
2. Column order
Physical structure Logical structure
Loc(A[3,2,2])= 1000+2(3*3*(2-1)+3*(2-1)+3-1)
= 1000 + 2(9+3+2)
= 1028
H.W.
You have the matrix A [5,3,2] ,by using two method of arrange matrix in memory:
a. Draw logical structure and physical structure of the matrix A.
b. find the address of the element A [2, 2,3].
In general, we can find out the location of any element in array (NXMXRXl) by using
following formulas:
In case of Row Major Order:
LOC (A [i,j,k,l]) = Base (A) + w (NMR(l-1)+NM(k-1)+M(i-1)+j-LB)
In case of Column Major Order:
LOC (A [i,j,k,l]) = Base (A) + w (NMR(l-1)+NM(k-1)+N(j-1)+i-LB)
Triangular Matrix
A triangular matrix is a special kind of square matrix. A square matrix is called
lower triangular if all the entries above the main diagonal are zero. Similarly, a
square matrix is called upper triangular if all the entries below the main diagonal are
zero.
Data Structures Academic Year 2017-2018
Address Elements
Address Elements
2. Lower triangular
In case of Row Major Order:
Loc (A [i,j]) =Base(A) + w((i-1) * i /2 + ([j-1))
Address Elements
Address Elements
where:
n is dimensions of the array
U : upper bound for dimension i
L: lower bound for dimension i
Data Structures Academic Year 2017-2018
Example1: Find the number of positions required to store the array: A [5]
=5-0+1=6
Example2: Find the number of positions required to store the matrix: A [5, 6]
(5-0+1)*(6-0+1)=6*7=42
int arr[6] = {10, 20, 30, 40}; //Array declaration by specifying size and initializing
elements
▪ Array elements are accessed by using an integer index. Array index starts
with 0 and goes till size of array minus 1. Following are few examples.
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3/2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];
In C it is not compiler error to initialize an array with more elements than specified
size.
int arr[2] = {10, 20, 30, 40, 50};
while in C++ , the program generates compiler error “error: too many initializes for
‘int [2]'”
Data Structures Academic Year 2017-2018
Arrays in Java
Arrays in Java work differently than they do in C/C++. Following are some
important point about Java arrays.
▪ In Java all arrays are dynamically allocated.
▪ Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using sizeof.
▪ A Java array variable can also be declared like other variables with [] after the
data type.
▪ The variables in the array are ordered and each have an index beginning from 0.
In Java, all objects are dynamically allocated on Heap. This is different from C++
where objects can be allocated memory either on Stack or on Heap. In C++, when we
allocate object using new(), the object is allocated on Heap, otherwise on Stack if not
global or static.
In Java, when we only declare a variable of a class type, only a reference is created
(memory is not allocated for the object). To allocate memory to an object, we must
use new(). So the object is always allocated memory on heap.
One-Dimensional Arrays :
The general form of a one-dimensional array declaration is:
type var-name[];
OR
type[] var-name;
Example:
// both are valid declarations
int intArray[]; or int[] intArray;
float floatArray[];
double doubleArray[];
char charArray[];
Although the above first declaration establishes the fact that intArray is an array
variable, no array actually exists. It simply tells to the compiler that this(intArray)
variable will hold an array of the integer type. To link intArray with an actual,
physical array of integers, you must allocate one using new and assign it to intArray.
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and var-name is the name of array variable that is linked to
the array. That is, to use new to allocate an array, you must specify the type and
number of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Note :
1. The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for boolean), or null (for reference types).
2. Obtaining an array is a two-step process. First, you must declare a variable of
the desired array type. Second, you must allocate the memory that will hold the
array, using new, and assign it to the array variable. Thus, in Java all arrays are
dynamically allocated.
Array Literal
In a situation, where the size of the array and variables of array are already known,
array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal
▪ The length of this array determines the length of the created array.
▪ There is no need to write the new int[] part in the latest versions of Java
Two-Dimensional Arrays :
In Java Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other array. For example, 2D array is a 1D array of
references to 1D arrays, each of these 1D arrays (rows) can have a different length,
this 2D array is called "Jagged array".
Examples of declare two-dimensional array:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Data Structures Academic Year 2017-2018
String in java
In java, string is basically an object that represents sequence of char values. it is
often implemented as:
▪ an array that stores a sequence of elements or as a reference type ,
mean string variable holds the address of the memory location where
the actual body of the string is stored.
For example:
▪ Java Strings can't change the characters, but string variables can point to
different strings:
String s;
s = "java language";
s = "java is oop";
String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance is returned.
If string doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any
string object with the value "Welcome" in string constant pool, so it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will
not create new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant
pool.
new keyword
In the following shown example of create string by using new keyword:
Data Structures : Strings Dr. Raidah Salim
Each time a new declaration a compiler would create different object in memory
Example:
String str1 = new String("Hello");
String str2 = new String("Hello");
In this case compiler would create two different object in memory having the same
text.
Assignment of string:
While primitive types are value types:
int x = 5;
The memory of x and y both
int y = x; contain "5".
A dynamic data structure , where in with the latter the size of the structure can
dynamically grow or shrink in size as needed. Linked lists are example of dynamic
data structure.
Linked Lists
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements
are not stored at contiguous location; the elements are linked using pointers. It
consists of group of nodes in a sequence which is divided in two parts. Each node
consists of its own data and the address of the next node and forms a chain. Linked
Lists are used to create trees and graphs.
Easy access to any element in No easy access to i-th element , need to hop through all previous
constant time elements start from start
• Doubly Linked List : In a doubly linked list, each node contains two links the first
link points to the previous node and the next link points to the next node in the
sequence.
• Circular Linked List : In the circular linked list the last node of the list contains the
address of the first node and forms a circular chain.
Basic Operations
More useful operations on linked list are:
• Inserting a particular Node from the List
• Checking whether Linked List is empty or not.
• Searching any element in the Linked List
• Deleting a particular Node from the List
Disadvantages:
▪ Requires more space.
▪ List manipulations are slower (because more links must be changed)
▪ Greater chance of having errors (because more links must be
manipulated)
class DListNode {
class DLL {
int data;
node head;
DListNode prior, next;
public DLL() {
}// DListNode
this.head = null;}
// methods
}
code segments in java to processing double linked list:
public class DNode {
int data;
DNode next, prev;
DNode(int data){
this.data=data;
next = null;
prev = null; }
}
void printDLL(){
for (DNode p=head; p!=null; p=p.next)
System.out.print(p.data + " ");
System.out.println();
}
void RprintDLL(){
DNode p;
for (p=head; p.next!=null; p=p.next){}
for (; p!=null; p=p.prev)
System.out.print(p.data + " ");
System.out.println(); }
else{
p.next=c;
DNode q=c.prev;
q.next=p;
p.prev=q;
c.prev=p;}
}
}
Both singly linked list and doubly linked list can be made into as circular linked list:
▪ Singly linked list as circular, the next pointer of the last node points to the
first node.
▪ Doubly linked list as circular, the next pointer of the last node points to the
first node and the previous pointer of the first node points to the last node
making the circular in both directions
To construct circular linked list we need define two class:
1. node class
2. circular linked list class(CLL)
class CLL {
class Node {
node head;
int data;
node next;
public CLL() {
node(int data) { this.head = null;
this.data = data;
} }
} // methods
...
}
code segments in java to processing circular linked list
public class CirclLL {
Node head;
CirclLL(){
head=null;
}
void printList(){
Node p;
for (p=head; p.next!=head; p=p.next ) {
System.out.print(p.data+" ");
}
System.out.println(p.data+"\n");
}
void addItem( int data){
Node p= new Node(data);
Node c=head;
if (head==null){
head=p;
p.next=head;}
else{
for (c=head; c.next!=head; c=c.next){}
c.next=p;
p.next=head;}
}
else{
while (cur.data!=item && cur.next!=head){
prv=cur;
cur=cur.next; }
if ( cur.next==head && cur.data==item){
p.next=cur;
prv.next=p;
}
else if (cur.next==head)
addItem(data);
else{
p.next=cur;
prv.next=p;}
}
}
Status of stack
Position of Top Status of Stack
-1 Stack is Empty
Storage(physical) Structure
Storage structure depends on the implementation of stack , array or linked list
structure.
Data Structures: Stack Dr. Raidah Salim
Implementation of Stack
Stack can be easily implemented using an Array or a Linked List. Arrays are quick,
but are limited in size and Linked List requires overhead to allocate, link, unlink, and
deallocate, but is not limited in size.
int pop(){
if (top < 0) {
System.out.println( "Stack Underflow");
return 0; }
else {
int d = listArray[top];
top--;
return d; }
}
}
Data Structures: Stack Dr. Raidah Salim
class StackLinkedList {
node top = null;
node pop() {
if (top == null){
System.out.println( " Stack is Empty.... ");
return top;}
else{
node p = top;
top = top.next;
return p;}
}
void peek(){
if (top == null)
System.out.println("The Stack is Empty....");
else
System.out.println (top.data);}
void clear() {
if (top == null) System.out.println("The Stack is Empty....");
else top = null; }
Data Structures: Stack Dr. Raidah Salim
void displayStack() {
node current = top;
while (current != null) {
System.out.print(current.data);
System.out.print(" ");
current = current.next; }
}
}
Example:
Applications of Stack
1. Reverse a word: You push a given word to stack - letter by letter - and then pop
letters from the stack.
2. Expression Conversion and evaluating expressions.
3. Call subprogram and recursion processing
Notes:
1. Postfix expressions are easier to process by machine than are infix expressions.
and it used in stack to evaluate the expressions.
2. Each operator has precedence as shown in the following table
Operator Precedence
() Highest
^
*,/ Lowest
+, −
Or
Expression Stack Output Action
Operator (RPN)
a+b/c Empty -
+b/c Empty a
b/c + a Push +
/c + ab
C +/ ab Push /
Empty +/ abc
Empty + abc/ Pop /
Empty Empty abc/+ Pop +
Or
Expression Stack Output Action
Operator (RPN)
a+b+c+d Empty -
+b+c+d Empty a
b+c+d + a Push +
+c+d + ab
+c+d Empty ab+ Pop +
c+d + ab+
+d + ab+c
+d Empty ab+c+ Pop +
d + ab+c+
Empty + ab+c+d
Empty Empty ab+c+d+ Pop +
Data Structures: Stack Dr. Raidah Salim
Notes:
At the end, there should be only one element left on the stack.
This assumes the postfix expression is valid.
Exercises: Convert the following infix expressions to postfix then evaluates these
postfix expressions, giving the stack contents after each step:
1. a/b+c/d
2. (a + b) * (c + d)
3. ((a + b) * c) - d
4. ( 80 – 30 ) * ( 40 + 50 / 10 )
5. ( a + b ) – ( c / ( d + e ) )
6. a / ( ( b / c ) * ( d – e ) )
7. ( a / ( b / c ) ) * ( d – e )
8. a * b + c ) / d – e )
9. (a – b) / ( c * ( d + e ) )
10. a / ( b + ( c * ( d – e ) ) )
11. (((2 * 5) - (1 * 2)) / (11 - 9))
12. (2 * 5 - 1 * 2) / (11 - 9)
13. A + B * C / D - E
14. A + B * (C - D) ) / E