0% found this document useful (0 votes)
89 views49 pages

Data Structures Course Overview 2017-2018

This document provides an overview of data structures. It defines data structures as a way to organize and store data in a computer so it can be efficiently accessed and modified. The document then describes several common data structures including arrays, linked lists, stacks, queues, and trees. It explains how data structures can be classified based on characteristics like being linear or non-linear, homogeneous or non-homogeneous, static or dynamic. The document focuses on arrays, providing details on their logical and physical structure for both single-dimensional and two-dimensional arrays. It describes how to calculate the memory location of elements in arrays.

Uploaded by

doaah hakim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views49 pages

Data Structures Course Overview 2017-2018

This document provides an overview of data structures. It defines data structures as a way to organize and store data in a computer so it can be efficiently accessed and modified. The document then describes several common data structures including arrays, linked lists, stacks, queues, and trees. It explains how data structures can be classified based on characteristics like being linear or non-linear, homogeneous or non-homogeneous, static or dynamic. The document focuses on arrays, providing details on their logical and physical structure for both single-dimensional and two-dimensional arrays. It describes how to calculate the memory location of elements in arrays.

Uploaded by

doaah hakim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

College of Computer Science and information

Technology

Data Structures

Lecturer: Dr. Raidah Salim


Data Structures Academic Year 2017-2018

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.

Basic types of Data Structures


Anything that can store data can be called as a data structure, hence integer,
float, boolean, char etc, all are data structures. They are known as Primitive Data
Structures.
Then we also have some complex Data Structures(Abstract Data Structures),
which are used to store large and connected data. Some example of Abstract Data
Structures are :
• Linked List
• Tree
• Graph
• Stack, Queue

The data structures can also be classified on the basis of the following
characteristics:

Characteristic Description

Linear In Linear data structures, the data items are arranged in a


linear sequence. Example: Array

Non-Linear In Non-Linear data structures, the data items are not in


sequence. Example: Tree, Graph

Homogeneous In homogeneous data structures, all the elements are of


Data Structures Academic Year 2017-2018

same type. Example: Array

Non- In Non-Homogeneous data structure, the elements may or


Homogeneous may not be of the same type. Example: Structures

Static Static data structures are those whose sizes and structures
associated memory locations are fixed, at compile time.
Example: Array

Dynamic Dynamic structures are those which expands or shrinks


depending upon the program need and its execution.
Example: Linked List

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

Classification according to Allocation memory :


Static memory allocation means the program must obtain its space before the
execution and cannot obtain more while or after execution.
Example: Arrays

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

All these data structures allow us to perform different operations on data:


1. Traversing: It is used to access each data item exactly once.
2. Searching: It is used to find out the location of the data item.
3. Inserting: It is used to add a new data item in the given collection of data
items.
4. Deleting: It is used to delete an existing data item from the given collection of
data items.
5. Sorting: It is used to arrange the data items in some order i.e. in ascending or
descending order.

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

Arrays data structure

An array is collection of items stored at continuous memory locations. The idea is


to store multiple items of same type together. This makes it easier to calculate the
position of each element by simply adding an offset to a base value(the memory
location of the first element of the array). Each element can be uniquely identified by
their index in the array.

Types of indexing in array:


▪ 0 (zero-based indexing): The first element of the array is indexed by subscript of
0
▪ 1 (one-based indexing): The first element of the array is indexed by subscript of
1
▪ n (n-based indexing): The base index of an array can be freely chosen. Usually
programming languages allowing n-based indexing also allow negative index
values and other scalar data types like enumerations, or characters may be used
as an array index.

Features of Arrays : An array is :


▪ Linear data structure: means organize in memory as linear order.
▪ homogeneous structure: all components in the structure are of the same
data type.
▪ finite structure : indicates that there is a last element.
▪ fixed size structure: mean that the size of the array must be known at
compile time.
▪ contiguously data structure: means that there is a first element, a second
element, and so on.
▪ The component selection mechanism of an array is direct access(random
access), which means we can access any element directly (by using specific
equation), without first accessing the preceding elements. This makes accessing
elements by position faster.

A one-dimensional array is homogeneous structure, it can be visualized as a list.


Logical structure for one-dimensional array with 15 elements as shown below:
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

H.w. : Suppose the following declaration:


int A[6];
1. Draw the logical structure and physical structure for the array A.
2. Find Loc(A(5)) , where the first element of the array A =200.
Data Structures Academic Year 2017-2018

A two-dimensional array is also homogeneous structure, it can be visualized as a


table consisting of rows and columns. The element in a two-dimensional array is
accessed by specifying the row and column indexes of the item in the array. Logical
Level for two-dimensional array with 3(0-2) rows and 4(0-3)column elements will
appear as shown below:

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.

Example: The following array:

A would be stored as follows in the two orders:

We can find out the location of any element in array (NXM) by using following
formulas:

1. In case of Row Major Order:


Loc (A [i, j]) = Loc (A [1,1]) +( [i-1]*M+ [ j-1 ]) * w
where:

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.

Example: finding the location (address) of element in 2D


Suppose A 3 x 4 (N=3 and M=4) integer array A is show as below and base address
= 1000 and number of bytes=2. find the location of A [3,2]:
Data Structures Academic Year 2017-2018

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

2. In case of Column Major Order:

Loc (A [i,j]) = Loc (A [1, 1]) + ([j-1]*N+ [i-1])*w


where
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.
N: is the total number of rows in the array.

Example: finding the location (address) of element in 2D


Suppose A 3 x 4 (N=3 and M=4) integer array A and base address =1000 and
number of bytes=2. find the location of A [3,2]:
Address Elements

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

Note: if the value of w not determine, it suppose equal to 1.

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

In case of Row Major Order:


Loc (A [i,j,k]) = Loc (A [1, 1, 1]) + ([k-1]*N*M+ [i-1]*M+ (j-1))*W

In case of Column Major Order:


Loc (A [i,j,k]) = Loc (A [1, 1, 1]) + ([k-1]*N*M+ [j-1]*N+ (i-1))*W

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

We can find out the location of a[2,2]by using following formulas:


1. Upper triangular
In case of Row Major Order:
Loc (A [i, j]) = Base(A) + w( ( (i-1)*M - (i-1)*i/2) + (j-1) )

Address Elements

1000 44 suppose Base (A)=1000 , i=2, j=2 and w=2


150 LOC (A [2,2]) = 1000 + 2*((2-1)*3-(2-1)*2/2+2-1)
1002
58 = 1000 + 2(3-1+1)
1004
34 = 1000 + 2*3
1006
24 = 1000 + 6
1008
= 1006
1010 33

In case of Column Major Order:


Loc (A[ i, j]) = Base(A) + w( (j-1) *j / 2 + ( i-1 ) )
Data Structures Academic Year 2017-2018

Address Elements

1000 44 suppose Base (A)=1000 , i=2, j=2 and w=2


150 LOC (A [2,2]) = 1000 + 2*((2-1)*2/2+2-1)
1002
34 = 1000 + 2(1+1)
1004
58 = 1000 + 2*2
1006
24 = 1000 + 4
1008
= 1004
1010 33

2. Lower triangular
In case of Row Major Order:
Loc (A [i,j]) =Base(A) + w((i-1) * i /2 + ([j-1))

Address Elements

1000 44 suppose Base (A)=1000 , i=2, j=2 and w=2


58 LOC (A [2,2]) = 1000 + 2*((2-1)*2/2+2-1)
1002
34 = 1000 + 2(1+1)
1004
150 = 1000 + 2*2
1006
24 = 1000 + 4
1008
= 1004
1010 33

In case of Column Major Order:


Loc (A [i,j]) = Base(A) + w( ( (j-1) *N - (j-1)*j/2 ) +(i-1))

Address Elements

1000 44 suppose Base (A)=1000 , i=2, j=2 and w=2


58 LOC (A [2,2]) = 1000 + 2*((2-1)*3 - (2-1)*2/2+2-1))
1002
150 = 1000 + 2(3-1+1)
1004
34 = 1000 + 2*3
1006
24 = 1000 + 6
1008
= 1006
1010 33

Q: How determine the number of array elements?


Ans.: To determine the number of any array elements by applying the following equation:

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

Example3: Find the number of positions required to store the matrix:


A[2..5, 6...8]

= (5-2+1)*(8-6+1) = 4*3 =12

Arrays in programming languages


Arrays in C, C++
▪ we can declare an array by specifying its and size or by initializing it or by
both. For Example:
int arr[10]; // Array declaration by specifying size
int arr[] = {10, 20, 30, 40}; //Array declaration by initializing elements.. Compiler
creates an array of size 4.

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];

▪ There is no index out of bound checking in C and C++:


int arr[2];
cout<< arr[3];

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

▪ In C/C++, initialization of a multidimensional arrays can have left most


dimension as optional. Except the left most dimension, all other dimensions
must be specified. For example:
int a[][2] = {{1,2},{3,4}};

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.

Instantiating an Array in Java


When an array us declared, only a reference of array is created. To actually create or
give memory to array, you create an array like this: The general form of new as it
applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Data Structures Academic Year 2017-2018

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

Q:How to delete and insert an element from array?


Ans.: Insertion and deletion at particular position is complex, it require shifting as in
the following examples.
Data Structures Academic Year 2017-2018

Insert item to sorted array

Q: Write a program to insert item to sorted array.

Q: What happens if we try to access element outside the array size?


Ans: Compiler error, indicate that array has been accessed with an illegal index. The
index is either negative or greater than or equal to size of array.
class example{
public static void main (String[] args){
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;
for (int i = 0; i <= arr.length; i++)
System.out.println(arr[i]);}}

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

Example: In the following memory layout of a jagged array numArr.


int[][] numArr = { {1,2,3}, {4,5,6,7}, {8,9} };

And jagged arrays can be created with the following code:


int [][]c;
c=new int[2][];
c[0]=new int[5];
c[1]=new int[3];
Data Structures : Strings Dr. Raidah Salim

Strings data structures


A string is collection of characters grouped together. For example, "hello" is a
string consisting of the characters 'h', 'e', 'l', 'l', and 'o'.
In most programming languages, strings are generally understood as a data type
are built in as part of the language and they take one of two basic representations as
illustrated in following figures:
1. null-terminated representation, in this, strings are represented as an array of
characters that ends with the special null terminator $.
2. pointer/length representation, in this representation a string is represented as (a
pointer to) an array of characters along with a integer that stores the length of the
string. The pointer/length representation is more efficient for some operations. For
example, in the pointer/length representation, determining the length of the string
takes constant time, since it is already stored.

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:

char[] ch={'j','a','v','a','i','s','o','o','p'}; is same as:


String s=new String(ch); String s="javaisoop";

▪ Java Strings can't change the characters, but string variables can point to
different strings:
String s;
s = "java language";
s = "java is oop";

Q: How to create String object?


There are two ways to create String object:
1. By string literal
2. By new keyword
Data Structures : Strings Dr. Raidah Salim

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.

Q: Why java uses concept of string literal?


Ans.: To make Java more memory efficient (because no new objects are created if it
exists already in 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.

Q: What is the output of the following program?


public class StringExample{
public static void main(String args[]){
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

Java String class methods


The java.util.String class provides many useful methods to perform operations on
sequence of char values.
Data Structures : Strings Dr. Raidah Salim
Data Structures : Strings Dr. Raidah Salim

Assignment of string:
While primitive types are value types:
int x = 5;
The memory of x and y both
int y = x; contain "5".

But with reference type:

String x = "a"; The memory of x and y both


String y = x; contain a pointer to the
character "a"
Linked List Data Structure
Static and Dynamic data structures
A static data structure is an organization of collection of data that is fixed in size.
This results in the maximum size needing to be known in advance ("‫)مسبقا‬, as memory
cannot be reallocated at a later. Arrays are example of static data structure.

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.

What are different between linked lists and arrays?

Arrays Linked lists


Have a pre-determined fixed No fixed size; grow one element at a time
size
Array items are store Element can be stored at any place
contiguously

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

Size = n x sizeof(element) Size = n x sizeof (element) + n x sizeof(reference)


Insertion and deletion at Insertion and deletion are simple and faster
particular position is
complex(shifting)
Only element store Each element must store element and pointer to next element
(extra memory for storage pointer).
Q: Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have following
limitations.
1) The size of the arrays is fixed.
2) Inserting a new element in an array of elements is expensive.

Advantages of Linked Lists


1) Dynamic size
2) Ease of insertion/deletion

Disadvantages of Linked Lists


1) Random access is not allowed.
2) Extra memory space for a pointer is required with each element of the list.

Applications of Linked Lists


Linked lists are used to implement stacks, queues, graphs, etc.

Types of Linked Lists


• Singly (Linear) Linked List : Singly linked lists contain nodes which have a data
part as well as an address part i.e. next, which points to the next node in
sequence of nodes.

• 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

Singly Linked List


In the following figure shown some operation on singly linked list :
To construct singly linked list we need define two class:
1. node class
2. singly linked list class(SLL)
class SLL {
class Node { node head;
int data;
node next; public SLL() {
this.head = null;}
node(int data) {
// methods
this.data = data;}
}
}
}
In the following steps for create linked list with data(22, 33, 44, 55,66)
or
node head = new node(22); head = new node(22);
head.next = new node(33); node p= head;
head.next.next = new node(44); p.next = new node(33);
head.next.next.next = new node(55); p = p.next;
head.next.next.next.next = new node(66);
p.next = new node(44);
p = p.next;
p.next = new node(55);
p = p.next;
p.next = new node(66);

Some code segments in java to processing singly linked list


// method to print elements of singly linked list
public void printSLL() {
for (node p = head; p != null; p = p.next) {
System.out.print(p.data + " "); }
}

// method for adding new node OR


void addLast ( int value){
void addLast(int value){
node newNode = new node(value);
node p;
node p = head;
node newNode = new node(value);
if (head == null)
if (head==null)
head = newNode;
head=newNode;
else {
else {
for (p = head; p.next!= null; p=p.next)
while (p.next != null)
{}
p = p.next;
p.next=newNode;
p.next = newNode;
}
}
}
}

// method to delete first element OR


public void deleteFirst() { public void deleteFirst() {
head = head.next; node curr = head;
head = head.next;
}
curr.next = null;
curr = null;}
//method to delete element after element in the list
public void deleteAfter(int value) {
node p = head;
while (p.data != value)
p = p.next;
node curr=p.next;
p.next= curr.next;
}

// method to add an element after an item of the list


public void addAfter(int value, int newValue) {
node p = head;
while (p.data != value)
p = p.next;
node newNode = new node(newValue);
newNode.next = p.next;
p.next = newNode;}

code segments in java to processing singly linked list:

public class SingleLL { public class Node {


Node head; int data;
SingleLL(){ Node next;
head=null;
} Node(int data){
this.data=data;
void printList(){ next=null;}
for (Node p=head; p!=null; p=p.next ) { }
System.out.print(p.data+" ");
}
System.out.println();
}

void addItem( int data){


Node p= new Node(data);
Node c=head;
if (head==null)
head=p;
else{
for (c=head; c.next!=null; c=c.next){}
c.next=p;}
}

void addBefore(int data, int item){


Node p=new Node(data);
Node cur=head;
Node prv=head;
if (head.data==item){
p.next=head;
head=p;}
else{
while (cur.data!=item && cur.next!=null){
prv=cur;
cur=cur.next; }
if (cur.next==null)
addItem(data);
else{
p.next=cur;
prv.next=p;}
}
}
void addAfter(int data, int item){
Node p=new Node(data);
Node cur=head;
while (cur.data!=item && cur.next!=null)
cur=cur.next;
if (cur.next==null) addItem(data);
else {
p.next=cur.next;
cur.next=p;}
}

void deleteItem(int item){


Node cur=head;
Node prv=head;
if (head.data==item)
head=cur.next;
else{
while (cur.data!=item && cur.next!=null){
prv=cur;
cur=cur.next;
}
if (cur.next==null && cur.data==item) prv.next=null;
else if (cur.next==null)
System.out.println(item+ " not found");
else
prv.next=cur.next;
}
}
}
Doubly linked lists
In this type of linked list each node contains a pair of references. One reference
points to the node that precedes the node (prior) and the other points to the node
that follows the node (next).
Advantages:
▪ Can be traversed in either direction.
▪ Some operations, such as deletion and inserting before a node,
become easier.

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)

In the following figure shown some operation on double linked list :


To construct double linked list we need define two class:

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; }
}

public class DoubleLL {


DNode head=null;
DoubleLL(){
head=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(); }

void addItem(int data){


DNode p = new DNode(data);
DNode c;
if (head==null)
head=p;
else{
for (c=head; c.next!=null; c=c.next){}
c.next=p;
p.prev=c;}
}

void addAfter(int data, int item){


DNode p= new DNode(data);
DNode c=head;
while (c.data!=item && c.next!=null)
c=c.next;
if (c.next==null && c.data!=item)
System.out.println(item + " not found");
else if (c.next==null)
addItem(data);
else{
p.next=c.next;
c.next.prev=p;
c.next=p;
p.prev=c;}
}

void addBefore(int data, int item){


DNode p=new DNode(data);
DNode c=head;
if (head.data==item){
p.next=head;
head.prev=p;
head=p;}
else {
while (c.data!=item && c.next!=null)
c=c.next;
if (c.data!=item && c.next==null)
System.out.println(item + " not found");

else{
p.next=c;
DNode q=c.prev;
q.next=p;
p.prev=q;
c.prev=p;}
}
}

void deleteItem(int item){


DNode p=head;
if (head.data==item){
head.next.prev=null;
head=head.next;
}
else {
while (p.data!=item && p.next!=null)
p=p.next;
if (p.data!=item && p.next==null)
System.out.println(item + " not found");
else if (p.data==item && p.next==null){
DNode q=p.prev;
q.next=null;}
else {
DNode q=p.prev;
q.next=p.next;
p.next.prev=q;
}
}

Circular Linked List


Circular Linked List is little more complicated linked data structure. In the circular
linked list the previous element stores the address of the next element and the last
element stores the address of the starting element. The elements points to each
other in a circular way which forms a circular chain.

in this type of linked list:


▪ Last node references the first node
▪ Every node has a successor
▪ No node in a circular linked list contains null

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;}
}

void addBefore(int data, int item){


Node p=new Node(data);
Node cur=head;
Node prv=head;
if (head.data==item){
for (cur=head; cur.next!=head; cur=cur.next ) {}
p.next=head;
head=p;
cur.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;}
}
}

void addAfter(int data, int item){


Node p=new Node(data);
Node cur=head;
while (cur.data!=item && cur.next!=null)
cur=cur.next;
if (cur.next==head) addItem(data);
else {
p.next=cur.next;
cur.next=p;}
}

void deleteItem(int item){


Node cur=head;
Node prv=head;
if (head.data==item){
for (cur=head; cur.next!=head; cur=cur.next ) {}
head=head.next;
cur.next=head;}
else{
while (cur.data!=item && cur.next!=head){
prv=cur;
cur=cur.next;
}
if (cur.next==head && cur.data==item) prv.next=head;
else if (cur.next==head)
System.out.println(item+ " not found");
else
prv.next=cur.next;
}
}
}
Data Structures: Stack Dr. Raidah Salim

Stack data structure


Stack is a list of homogeneous items with a bounded(predefined) capacity. It is a
simple data structure that allows adding and removing elements in a particular
order. Every time an element is added, it goes on the top of the stack, the only
element that can be removed is the element that was at the top of the stack.

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO structure. (Last in First out).
3. push() function is used to insert new elements into the Stack and pop() function
is used to delete an element from the stack. Both insertion and deletion are
allowed at only one end of Stack called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.

Status of stack
Position of Top Status of Stack

-1 Stack is Empty

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

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.

 Implementation of stack using Array


The following figure shows implementation for stack using array:

In the following stack class:


class stack{
int top;
int listArray[]=new int[10]; //Maximum size of Stack
stack() {
top = -1;}

void push(int x){


if ( top >= 10) System.out.println( "Stack Overflow");
else{
top++;
listArray[top] = x;
System.out.println( "Element Inserted");}
}

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

 Implementation of stack using linked list


The following figure shows implementation for stack using linked list:

In the following stack class:

class StackLinkedList {
node top = null;

void push(int data) {


node p = new node(data);
if (top == null)
top = p;
else{
p.next = top;
top = p; }
}

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

 Converting and Evaluating Expressions


Arithmetical operations like addition, subtraction, multiplication, and division are
called binary operations because they each combine two operands:
Operand operator operand
There are three type for operator notations : Infix, prefix and postfix(also called
reverse Polish notation, or RPN) . for example consider the simple binary operation
a + b Equivalent prefix and postfix forms are shown bellow:.
Prefix: + a b operator first
Postfix: a b + operator last
Data Structures: Stack Dr. Raidah Salim

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
+, −

 Convert Infix to Postfix Algorithm (in case expression NOT contain


parentheses)
Step 1: For each term in expression
Step 2: If term is an operator
Compare it with the operator on the top, if have the same or higher
precedence , Pop it, otherwise Push this operator into stack
Else Copy operand to output
end if
Step 3: Pop remaining operators and copy to output
Example 1: By using stack data structure convert Infix expression a + b / c to
Postfix expression
Data Structures: Stack Dr. Raidah Salim

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 +

Example 2: : By using stack data structure convert Infix expression a + b + c + d


to Postfix expression.

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

Exercises: Convert these infix expressions to postfix expressions:


1. a + b * c* d+ e
2. a * b + c * d* e* f
3. a / b / c + d * e * f
4. a+b*c^d/e-f*g
5. a-b+c*d/e

Algorithm to Convert an infix expression to postfix notation(in case expression


contain parentheses)
Suppose Q is an arithmetic expression(contain parentheses) in infix notation. We
will create an equivalent postfix expression P by adding items to on the right of P.

Start with an empty stack. We scan Q from left to right.


While (we have not reached the end of Q)
If (an operand is found)
Add it to P
end if
If (a left parenthesis is found)
Push it onto the stack
end if

If (a right parenthesis is found)


While (the stack is not empty AND the top item is not a left
parenthesis)
Pop the stack and add the popped value to P
end while
Pop the left parenthesis from the stack and discard it
End-If
If (an operator is found)
If (the stack is empty or if the top element is a left parenthesis)
Push the operator onto the stack
Else
While (the stack is not empty AND the top of the stack
is not a left parenthesis AND precedence of the
operator <= precedence of the top of the stack)
Pop the stack and add the top value to P
End-While
Push the latest operator onto the stack
End-If
End-If
End-While
While (the stack is not empty)
Pop the stack and add the popped value to P
End-While
Note : At the end, if there is still a left parenthesis at the top of the stack, or if we
find a right parenthesis when the stack is empty, then Q contained unbalanced
parentheses and is in error.
Data Structures: Stack Dr. Raidah Salim

Example 3 : Convert the infix expressions to postfix:(2+3)*4

Expression Stack Output Action


Operator (RPN)
(2+3)*4 Empty -
2+3)*4 ( - Push (
+3)*4 ( 2
3)*4 (+ 2 Push +
)*4 (+ 23
*4 ( 23+ Pop +
*4 Empty 23+ Pop (
4 * 23+
Empty * 23+ 4
Empty Empty 23+4* Pop *

Example 4 : Convert the infix expressions to postfix:2+(3*4)

Expression Stack Output Action


Operator (RPN)
2+(3*4) Empty -
+(3*4) Empty 2
(3*4) + 2 Push +
3*4) +( 2 Push(
*4) +( 23
4) +(* 23 Push*
) +(* 234
Empty +(* 234* Pop *
Empty +( 234* Pop (
Empty Empty 234*+ Pop +

Example 5: Convert the infix expressions to postfix:(3*2+4)^2


Expression Stack Output Action
Operator (RPN)
(3*2+4)^2 Empty -
3*2+4)^2 ( - Push(
*2+4)^2 ( 3
*2+4)^2 (* 3 Push *
+4)^2 (* 32
+4)^2 ( 3 2* Pop *
4)^2 (+ 32* Push +
)^2 (+ 3 2 *4
^2 ( 3 2* 4 + Pop +
^2 Empty 3 2 *4 + Pop (
2 ^ 3 2 *4 + Push ^
Empty ^ 3 2 *4+ 2
Empty Empty 3 2 *4 + 2 ^ Pop ^
Data Structures: Stack Dr. Raidah Salim

Algorithm to Evaluate a postfix expression


Suppose P is an arithmetic expression (contain parentheses )in postfix notation. We
will evaluate it using a stack to hold the operands.
Start with an empty stack. We scan P from left to right.
While (we have not reached the end of P)
If an operand is found
push it onto the stack
End-If
If an operator is found
Pop the stack and call the value A
Pop the stack and call the value B
Evaluate B op A using the operator just found.
Push the resulting value onto the stack
End-If
End-While
Pop the stack (this is the final value)

Notes:
 At the end, there should be only one element left on the stack.
 This assumes the postfix expression is valid.

Example 6 : consider the postfix expression : 3 5 1 - *

Expression Execute Stack Action


351-* Empty
51-* 3 Push 3
1-* 35 Push 5
-* 351 Push 1
* 34 Pop 1 and 5,Execute 5 - 1= 4 , Push 4
Empty 12 Execute 3 * 4 = 12, Push 12
Empty Empty Pop the result 12
Data Structures: Stack Dr. Raidah Salim

Example 7 : consider the postfix expression : 5 4 + 3 / 1 6* 2 +

Expression Execute Action


stack
5 4 + 3 / 1 6* + Empty
4 + 3 / 1 6* + 5 Push 5
+ 3 / 1 6* + 54 Push 4
3 / 1 6* + 9 Pop 5 and 4,Execute 5+4=9 , Push 9
1 6* + 93 Pop 9 and 3,Execute 9/3= 3 , Push 3
1 6* + 3 Pop 6 and 1, Execute 6/1 = 6, Push 6
6* + 31
*+ 316 Pop 1 and 6, Execute 6*1 = 6, Push 6
+ 36 Pop 3 and 6, Execute 3+6 = 9, Push9
Empty 9
Empty Empty Pop the result 9

Example8 : Evaluate the postfix expression : 3 2 *4 + 2 ^

Expression Execute Action


stack
3 2 *4 + 2 ^ Empty
2 *4 + 2 ^ 3 Push 3
*4 + 2 ^ 32 Push 2
4+2^ 6 Pop 3 and 2, Exeute2 *3=6, Push 6
+2^ 64 Push 4
2^ 10 Pop 6 and 4, Execute 6+4=10, Push 10
2^ 10 2 Push 2
^ 100 Pop 10 and 2, Exeute10^2=100, Push 100
Empty Empty Pop the result 100

Example9 : Evaluate the postfix expression : 2 3 4 * + 2 ^

Expression Execute Action


stack
234*+2^ Empty
34*+2^ 2 Push 2
4*+2^ 23 Push 3
*+2^ 234 Push 4
+2^ 2 Pop 3 and 4,Execute 3*4= 12,Push 12
+2^ 2 12
2^ 14 Pop 2 and 12, Execute 2+12=14, Push 14
^ 14 2 Push 2
Empty 196 Pop 14 and 2, Execute 14^2 = 196, Push196
Empty Empty Pop the result 196
Data Structures: Stack Dr. Raidah Salim

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

You might also like