0% found this document useful (0 votes)
5 views

DSA_Lecture Notes - Part 1

The document provides an overview of data structures in C++, covering input/output methods, functions, arrays, pointers, and memory management. It explains linear and non-linear data structures, including linked lists and their operations such as insertion and deletion. Additionally, it discusses the implementation of singly and doubly linked lists, detailing the steps for various operations.

Uploaded by

Kishore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DSA_Lecture Notes - Part 1

The document provides an overview of data structures in C++, covering input/output methods, functions, arrays, pointers, and memory management. It explains linear and non-linear data structures, including linked lists and their operations such as insertion and deletion. Additionally, it discusses the implementation of singly and doubly linked lists, detailing the steps for various operations.

Uploaded by

Kishore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Data Structures – Lecture Notes

C++ programming language


Input and output in C++
The standard C++ library is iostream and standard input / output functions in C++ are:
1.cin
2.cout
cin
It is the method to take input any variable / character / string.
Syntax:
cin>>variable / character / String / ;

cout
This method is used to print variable / string / character. Syntax:
cout<< variable / charcter / string;

Functions in C++
A function is a block of code that performs a specific task. It has a name and it is reusable i.e. it can
be executed from as many different parts as required. It also optionally returns a value to the calling
function.
A complex problem may be decomposed into a small or easily manageable parts or modules called
functions. Functions are very useful to read, write, debug and modify complex programs They can also
be incorporated in the main program. The main() itself is a function is invoking the other functions to
perfom various tasks.

return_type function_name(argument_list)
{ statement 1;
.
.
Statements n;
}

CALL BY VALUE
In call by value, value being passed to the function is locally stored by the function parameter in stack
memory location. If you change the value of function parameter, it is changed for the current function
only. It will not change the value of variable inside the caller method.
int main()
{
int data = 3; change(data);
cout << "Value of the data is: " << data<< endl; return 0;
}
void change(int data)
{
data = 5;
}

1
Call BY REFERENCE
In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments share the same
address space. Hence, value changed inside the function, is reflected inside as well as outside the
function.

#include<iostream> using
namespace std; void swap(int *x,
int *y)
{
int swap; swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl; cout<<"Value of y is:
"<<y<<endl;
return 0;
}

C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.
C++ Array Types
There are 2 types of arrays in C++ programming:
• Single Dimensional Array
• Multidimensional Array

#include <iostream> using


namespace std; int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.

2
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and
used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
2) Arrays, Functions and Structures
Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.
int main()
{
int number=30; int ∗ p;
p=&number;//stores the address of number variable cout<<"Address
of number variable is:"<<&number<<endl; cout<<"Address of p
variable is:"<<p<<endl; cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}

new and delete Operators


new is used to allocate memory for a variable, object, array, array of objects.. etc at run time. "To
declaring memory at run time is known as dynamic memory allocation." we use memory by this
method (dynamic allocation) when it is not known in advance how much memory space is needed.
since "these operators manipulate memory on the free store, so they are also known as free store
operators. the new operator can be used to create objects of any type, it takes the following general
form:
pointer_variable = new data_type;

delete Operator :
delete operator is used to Deallocates the dynamically allocated memory.

Since the necessity of dynamic memory is usually limited to specific moments within a program, once
it is no longer needed it should be freed so that the memory becomes available again for other requests
of dynamic memory. This is the purpose of the operator delete.
delete takes the following general form:
1. delete pointer_variable;
2. delete []pointer_variable;

#include<iostream.h>
void main()
{
3
int size,i; int *ptr;
cout<<"\n\tEnter size of Array : "; cin>>size;
ptr = new int[size];
for(i=0;i<5;i++) //Input arrray from user.
{

4
cout<<"\nEnter any number : "; cin>>ptr[i];
}

for(i=0;i<5;i++) //Output arrray to console.


cout<<ptr[i]<<", ";

delete[] ptr;
//deallocating all the memory created by new operator

What is Data Structure?


Data may be organized in many different ways: The logical or mathematical model of a particular
organization of data is called data structure.
Data structures are divided into two types.
• Linear Data Structures
• Non - Linear Data Structures

Linear Data Structures


If a data structure is organizing the data in sequential order, then that data structure iscalled as Linear Data
Structure. For example:
• Arrays
• Lists (Linked List)
• Stacks
• Queues
Non - Linear Data Structures
If a data structure is organizing the data in random order, then that data structure is called as Non-Linear
Data Structure. For example:
• Trees
• Graphs

Array as an ADT
The array is a basic abstract data type that holds an ordered collection of items accessible by an integer
index. Since it's an ADT, it doesn't specify an implementation, but is almost always implemented by an
array data structure or dynamic array.

SINGLY LINKED LIST


A singly linked list, or simply a linked list, is a linear collection of data items. The linear order is
given by means of POINTERS. These types of lists are often referred to as linear linked list.
*Each item in the list is called a node.
*Each node of the list has two fields:
1. Information- contains the item being stored in the list.
2. Next address- contains the address of the next item in the list.

5
*The last node in the list contains NULL pointer to indicate that it is the end of the list. Conceptual
view of Singly Linked List

data ptr data ptr data null

Operations on Singly linked list:


• creation
• Insertion of a node
• Deletions of a node
• Traversing the list
Structure of a node: Method -1:
struct node { int
data; data link
struct node *link;
};
Method -2:
class node {
public:
int data; node
*link;
};
Insertions: To place an elements in the list there are 3 cases :
1. At the beginning
2. End of the list
3. At a given position
case 1:Insert at the beginning
head 4 x 5 6

temp
head is the pointer variable which contains address of the first node and temp contains address of
6
new node to be inserted then sample code is

After insertion

2 4 5 6

struct Node
{
int data;
struct Node *next;
};
struct Node *head = NULL;
void insert(int value)
{
struct Node *newnode = new Node();
newnode -> data = value;
if(head==NULL)
{
newnode -> next = NULL;
head = newnode;
}
else
{
newnode -> next = head;
head = newnode;
}
}
case 2:Inserting end of the list

7
void insertatend(int value)
{
Node *newnode = new Node();
struct Node *temp = head;
newnode -> data = value;
newnode -> next = NULL;
if(head==NULL)
{
head = newnode;
return;
}
while(temp -> next!=NULL)
{
temp = temp -> next;
}
temp -> next = newnode;
};
case 3: Insert at a position

8
void insertatpos(int pos,int value){
int i;
struct Node *newnode = new Node();
newnode->data = value;
// newnode->next=NULL;
struct Node *temp = head;
for(i=1;i<pos;i++){
temp=temp->next;
}
newnode->next = temp->next;
temp->next = newnode;
}
Deletions: Removing an element from the list, without destroying the integrity of the list itself
To place an element from the list there are 3 cases :
1. Delete a node at beginning of the list
2. Delete a node at end of the list
3. Delete a node at a given position
Delete a node at beginning of the list

9
Delete a node at end of the list

• Step 1 - Check whether list is Empty (head == NULL)


• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.
• Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.
• Step 4 - Check whether list has only one Node (temp1 → next == NULL)
• Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate the function.
(Setting Empty list condition)
• Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat
the same until it reaches to the last node in the list. (until temp1 → next == NULL)
• Step 7 - Finally, Set temp2 → next = NULL and delete temp1.

Deleting a Specific Node from the list


We can use the following steps to delete a specific node from the single linked list...

• Step 1 - Check whether list is Empty (head == NULL)


• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.
• Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.
• Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the last
node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.
• Step 5 - If it is reached to the last node then display 'Given node not found in the list!
Deletion not possible!!!'. And terminate the function.
• Step 6 - If it is reached to the exact node which we want to delete, then check whether list is
having only one node or not
10
• Step 7 - If list has only one node and that is the node to be deleted, then set head = NULL and
delete temp1 (free(temp1)).
• Step 8 - If list contains multiple nodes, then check whether temp1 is the first node in the list
(temp1 == head).
• Step 9 - If temp1 is the first node then move the head to the next node (head = head → next)
and delete temp1.
• Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next
== NULL).
• Step 11 - If temp1 is last node then set temp2 → next = NULL and
delete temp1 (free(temp1)).
• Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 →
next and delete temp1 (free(temp1)).

A singly linked list has the disadvantage that we can only traverse it in one direction. Many
applications require searching backwards and forwards through sections of a list. A useful refinement
that can be made to the singly linked list is to create a doubly linked list.The distinction made between
the two list types is that while singly linked list have pointers going in one direction, doubly linked
list have pointer both to the next and to the previous element in the list. The main advantage of a
doubly linked list is that, they permit traversing or searching of the list in both directions.
In this linked list each node contains three fields.
• One to store data
• Remaining are self referential pointers which points to previous and next nodes in the list
prev data next
Implementation of node using structure
Method -1:
struct node
{
int data;
struct node *prev; struct
node * next;
};

Implementation of node using class Method -2:


class node
{
public:
int data; node
*prev; node *
next;
};

Operations on Double Linked List


In a double linked list, we perform the following operations...
• Insertion
11
• Deletion
• Display

Insertion
In a double linked list, the insertion operation can be performed in three ways as follows...
• Inserting At Beginning of the list
• Inserting At End of the list
• Inserting At Specific location in the list

Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the double linked list.
Step 1 - Create a newNode with given value and newNode → previous as NULL.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, assign NULL to newNode → next and newNode to head.
• Step 4 - If it is not Empty then, assign head to newNode → next and newNode to head.

Inserting At End of the list


We can use the following steps to insert a new node at end of the double linked list...
• Step 1 - Create a newNode with given value and newNode → next as NULL.
• Step 2 - Check whether list is Empty (head == NULL)
• Step3- If it is Empty, then assign NULL to newNode → previous and newNode to head.
• Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list
(until temp → next is equal to NULL).
• Step 6 - Assign newNode to temp → next and temp to newNode → previous.

Inserting At Specific location in the list (After a Node)


We can use the following steps to insert a new node after a node in the double linked list...
• Step 1 - Create a newNode with given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, assign NULL to both newNode → previous& newNode →
next and set newNode to head.
• Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and initialize
temp1 with head.
• Step 5 - Keep moving the temp1 to its next node until it reaches to the node after which we want
to insert the newNode (until temp1 → data is equal to location, here location is the node value
after which we want to insert the newNode).
• Step 6 - Every time check whether temp1 is reached to the last node. If it is reached to the last
node then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate
the function. Otherwise move the temp1 to next node.
• Step 7 - Assign temp1 → next to temp2, newNode to temp1 → next, temp1 to newNode →
previous, temp2 to newNode → next and newNode to temp2 → previous.

Deletion
12
In a double linked list, the deletion operation can be performed in three ways as follows...
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node

Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the double linked list...

• Step 1 - Check whether list is Empty (head == NULL)


• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.
• Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.
• Step 4 - Check whether list is having only one node (temp → previousis equal to temp →
next)
• Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty list conditions)
• Step 6 - If it is FALSE, then assign temp → next to head, NULL to head → previous and
delete temp.

Deleting from End of the list


We can use the following steps to delete a node from end of the double linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not possible' and terminate
the function.
• Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.
• Step 4 - Check whether list has only one Node (temp → previous and temp → next both
are NULL)
• Step 5 - If it is TRUE, then assign NULL to head and delete temp. And terminate from the
function. (Setting Empty list condition)
• Step 6 - If it is FALSE, then keep moving temp until it reaches to the last node in the list.
(until temp → next is equal to NULL)
• Step 7 - Assign NULL to temp → previous → next and delete temp.

Deleting a Specific Node from the list


We can use the following steps to delete a specific node from the double linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.
• Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.
• Step 4 - Keep moving the temp until it reaches to the exact node to be deleted or to the last
node.
• Step 5 - If it is reached to the last node, then display 'Given node not found in the list!
Deletion not possible!!!' and terminate the fuction.
• Step 6 - If it is reached to the exact node which we want to delete, then check whether list is
having only one node or not
• Step 7 - If list has only one node and that is the node which is to be deleted then
13
set head to NULL and delete temp (free(temp)).
• Step 8 - If list contains multiple nodes, then check whether temp is the first node in the list
(temp == head).
• Step 9 - If temp is the first node, then move the head to the next node (head = head → next),
set head of previous to NULL (head → previous = NULL) and delete temp.
• Step 10 - If temp is not the first node, then check whether it is the last node in the list (temp →
next == NULL).
• Step 11 - If temp is the last node then set temp of previous of next to NULL (temp →
previous → next = NULL) and delete temp(free(temp)).
• Step 12 - If temp is not the first node and not the last node, then
set temp of previous of next to temp of next (temp → previous → next = temp →
next), temp of next of previous to temp of previous (temp → next → previous = temp →
previous) and delete temp (free(temp)).

14
Circular Linked List
In a circular linked list, we perform the following operations...

• Insertion
• Deletion
• Display

• Step 1 - Include all the header files which are used in the program.
• Step 2 - Declare all the user defined functions.
• Step 3 - Define a Node structure with two members data and next
• Step 4 - Define a Node pointer 'head' and set it to NULL.
• Step 5 - Implement the main method by displaying operations menu and make suitable function
calls in the main method to perform user selected operation.

Insertion
In a circular linked list, the insertion operation can be performed in three ways. They are as
follows.Inserting At Beginning of the list
• Inserting At End of the list
• Inserting At Specific location in the list

Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the circular linked list...
• Step 1 - Create a newNode with given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, set head = newNode and newNode→next= head .
• Step 4 - If it is Not Empty then, define a Node pointer 'temp' and initialize with 'head'.
• Step 5 - Keep moving the 'temp' to its next node until it reaches to the last node (until 'temp →
next == head').
• Step 6 - Set 'newNode → next =head', 'head = newNode' and 'temp → next = head'.

Inserting At End of the list


We can use the following steps to insert a new node at end of the circular linked list...

• Step 1 - Create a newNode with given value.


• Step 2 - Check whether list is Empty (head == NULL).
• Step 3 - If it is Empty then, set head = newNode and newNode → next = head.
• Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list
(until temp → next == head).
• Step 6 - Set temp → next = newNode and newNode → next = head.

Inserting At Specific location in the list (After a Node)


15
We can use the following steps to insert a new node after a node in the circular linked list...
• Step 1 - Create a newNode with given value.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty then, set head = newNode and newNode → next = head.
• Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to the node after which we want
to insert the newNode (until temp1 → datais equal to location, here location is the node value
after which we want to insert the newNode).
• Step 6 - Every time check whether temp is reached to the last node or not. If it is reached to last
node then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate
the function. Otherwise move the temp to next node.
• Step 7 - If temp is reached to the exact node after which we want to insert the newNode then
check whether it is last node (temp → next == head).
• Step 8 - If temp is last node then set temp → next = newNode and newNode → next = head.
• Step 8 - If temp is not last node then set newNode → next = temp → next and temp →
next = newNode.

In a circular linked list, the deletion operation can be performed in three ways those are as follows...
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node

Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize both 'temp1'
and 'temp2' with head.

Step 4 - Check whether list is having only one node (temp1 → next == head)

Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting Empty list conditions)

Step 6 - If it is FALSE move the temp1 until it reaches to the last node. (until temp1 →
next == head )

Step 7 - Then set head = temp2 → next, temp1 → next = head and delete temp2.

16
Deleting from End of the list
We can use the following steps to delete a node from end of the circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.

Step 4 - Check whether list has only one Node (temp1 → next == head)

Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate from the
function. (Setting Empty list condition)

Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat the
same until temp1 reaches to the last node in the list. (until temp1 → next == head)

Step 7 - Set temp2 → next = head and delete temp1.

Deleting a Specific Node from the list

We can use the following steps to delete a specific node from the circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.

Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the last node.
And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.

Step 5 - If it is reached to the last node then display 'Given node not found in the list! Deletion
not possible!!!'. And terminate the function.

Step 6 - If it is reached to the exact node which we want to delete, then check whether list is having
only one node (temp1 → next == head)

Step 7 - If list has only one node and that is the node to be deleted then set head = NULL and delete
temp1 (free(temp1)).

Step 8 - If list contains multiple nodes then check whether temp1 is the first node in the list (temp1
17
== head).

Step 9 - If temp1 is the first node then set temp2 = head and keep moving temp2 to its next node
until temp2 reaches to the last node. Then set head = head → next, temp2 → next = head and delete
temp1.

Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next ==
head).

Step 1 1- If temp1 is last node then set temp2 → next = head and delete temp1 (free(temp1)).

Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 → next and delete
temp1 (free(temp1)).

STACK
Stack is a linear data structure and very much useful in various applications of computer science.
Definition
A stack is an ordered collection of homogeneous data elements, where the insertion and deletion
operation takes place at one end only, called the top of the stack.
Like array and linked list, stack is also a linear data structure, but the only difference is that in case
of former two, insertion and deletion operations can take place at any position.
In a stack the last inserted element is always processed first. Accordingly, stacks are called as
Last-in-First-out (LIFO) lists. Other names used for stacks are “piles” and “push-down
lists”.
Stack is most commonly used to store local variables, parameters and return addresses when a
function is called.

18
Stack Model of Stack
The variable top always keeps track of the top most element or position.

19
STACK OPERATIONS
• PUSH: “Push” is the term used to insert an element into a stack.
• POP: “Pop” is the term used to delete an element from a stack.
Two additional terms used with stacks are “overflow” & “underflow”. Overflow occurs when we
try to push more information on a stack that it can hold. Underflow occurs when we try to pop an
item from a stack which is empty.

REPRESENTATION OF STACKS
A stack may be represented in the memory in various ways. Mainly there are two ways. They are:
1. Using one dimensional arrays(Static Implementation)
2. Using linked lists(Dynamic Implementation)

Representation of Stack using Array


First we have to allocate a memory block of sufficient size to accommodate the full capacity of the
stack. Then, starting from the first location of the memory block, items of the stack can be stored in
sequential manner.
Top is a pointer to point the
position of array upto which it is filled with the items of stack. With
this representation following two statements can be stated:
EMPTY: Top<l FULL:
Top>=u+l-1

Algorithms for Stack Operations


Algorithm PUSH (STACK, TOP, MAXSTK, ITEM)
This algorithm pushes an ITEM onto a stack.
Step 1: If TOP = MAXST K, then: \\ Check Overflow? Print:
OVERFLOW, and Exit.
Step 2: Set TOP := TOP + 1. \\ increases TOPby 1
Step 3: Set STACK[TOP] := ITEM. \\ Inserts ITEM in new TOP position. Step
4: Exit.
Here we have assumed that array index varies from 1 to SIZE and Top points the location of the
current top most item in the stack.
Algorithm POP (STACK, TOP, ITEM)
This algorithm deletes the top element of STACK and assigns it to the variable ITEM. Step
1: If TOP = NULL, then: \\ Check Underflow.
Print: UNDERFLOW, and Exit.
Step 2: Set ITEM := STACK[TOP]. \\ Assigns TOP element to ITEM. Step 3:
Set TOP := TOP – 1. \\ Decreases TOP by 1.
Step 4: Exit.

20
Top is a pointer to point the position of array upto which it is filled with the items of stack. With
this representation following two statuses can be stated:
EMPTY: Top<l FULL:
Top>=u+l-1

Algorithm: POP_LINKSTACK(INFO, LINK, TOP, AVAIL, ITEM).


This algorithm deletes the top element of a linked stack and assigns it to the variable ITEM.

Step 1: If TOP = NULL, then: \\ Check Underflow?


Write: UNDERFLOW and Exit.
Step 2: Set ITEM := STACK[TOP]. \\ Copies the TOP element of STACK into ITEM. Step 3:
Set TEMP := TOP, and
TOP := LINK[TOP]. \\ Reset the position of TOP. Step 4:
[Add node to the AVAIL list.]
Set LINK[TEMP] := AVAIL, AVAIL := TEMP.
Step 5: Exit.

APPLICATIONS OF STACKS
1. Reversing elements in a list or string.
2. Recursion Implementation.
3. Memory management in operating systems.
4. Evaluation of postfix or prefix expressions.
5. Infix to postfix expression conversion.
6. Tree and Graph traversals.
7. Checking for parenthesis balancing in arithmetic expressions.
8. Used in parsing.

Arithmetic Expressions
An expression is a collection of operators and operands that represents a specific value. In above
definition,
□ Operator is a symbol (+,-,>,<,..) which performs a particular task like arithmetic or
logical or relational operation etc .,
□ Operands are the values on which the operators can perform the task.
Expression Types
Based on the operator position, expressions are divided into THREE types. They are as follows
:
1. Infix Expression
2. Postfix Expression
3. Prefix Expression

21
Infix Expression
In infix expression, operator is used in between operands. This notation is also called as polish
notation. The general structure of an Infix expression is:
operand <operator> operand eg: A+B

Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the
Operands". This notation is also called as reverse - polish notation. The general structure of Postfix
expression is:
operand <operator> Eg:AB+

Prefix Expression
In prefix expression, operator is used before operands. We can say that "Operands follows the Operator".
The general structure of Prefix expression is:
<Operator > operand operand Ex:+AB

In 2nd and 3rdnotations, parentheses are not needed to determine the order evaluation of the operations in
any arithmetic expression.
Eg.: Infix Prefix Postfix
1. A+B*C A+{*BC} A+{BC*}

+A*BC ABC*+ { } indicate partial translation

2. (A+B)*C {+AB}*C {AB+}*C


*+ABC AB+C*

The computer usually evaluates an arithmetic expression written in infix notation in two steps.
1. It converts the expression to postfix notation and
2. It evaluates the postfix expression.
In each step, the stack is the main tool that is used to accomplish the given task.
2.5.1 Transform ing Infix Expression into Postfix Expression
In the infix expression we assume only exponentiation (^ or **), multiplication(*), division(/),
addition (+), subtraction(-) operations. In addition to the above operators and operands they may
contain left or right parenthesis. The operators three levels of priorities are:
High priority : ^ or ** Next
high priority:*,/ Lowest +,-
The following algorithm transforms the infix expression Q into the equivalent postfix

22
expression P. The algorithm uses a stack to temporarily hold operators and left parenthesis.

ALGORITHM INF IX-TO-POSTF IX (Q)

Step1: Push „(„ onto stack and add „)‟ to the end of Q.
Step 2: Scan Q from left to right and repeat steps 3 to 6 for each element of Q until STACK is empty.
Step 3: If an operand is encountered, add it to P.
Step 4: If a left parentheses is encountered, push it onto STACK.
Step 5: If an operator Ө is encountered, then:
a) Repeatedly pop from STACK and add to P each operator (on the top of
STACK) which has the same precedence as or higher precedence than Ө.
b) Add Ө to the STACK
[End of If Structure]
Step 6: If a right parentheses is encountered, then:
a) Repeatedly pop from STACK and add to P each operator (on the top of
STACK) until a left parentheses is encountered.
b) Remove the left parenthesis. [Do not add this to P]
Step 7: Exit.

Consider the following infix expression Q: A + (B * C - (D / E ^ F) * G) * H

Symbol Scanned Stack Contents Expression P


Initial (
(1) A ( A
(2) + (+ A
(3) ( (+( A
(4) B (+( AB
(5) * (+(* AB
(6) C (+(* ABC
(7) - (+(- ABC *
(8) ( (+(-( ABC*
(9) D (+(-( ABC*D
(10) / (+(-(/ ABC*D
(11) E (+(-(/ ABC*DE
(12) ^ (+(-(/^ ABC*DE
(13) F (+(-(/^ ABC*DEF
(14) ) (+(- ABC*DEF^/
(15) * (+(-* ABC*DEF^/
(16) G (+(-* ABC*DEF^/G
(17) ) (+ ABC*DEF^/G*-

23
(18) * (+* ABC*DEF^/G*-
(19) H (+* ABC*DEF^/G*-H
(20) ) ABC*DEF^/G*-H * +

OUTPUT P: ABC*DE^/G*-H * + (POSTFIX FORM)

EVALUATION OF A POSTF IX EXPRESSION


Suppose P is an arithmetic expression written in postfix . The following algorithm uses a STACK
to hold operands during the evaluation of P.
Algorithm EVALPOSTF IX(p)
Step 1: Add a right parentheses „)‟ at the end of P. //this acts as a sentinel
Step 2: Scan P from left to right and repeat steps 3 and 4 for each element of P until the sentinel
„)‟ is encountered.
Step 3: If an operand is encountered, push on STACK. Step 4:
If an operator Ө is encountered, then:
a) Remove the two top elements of STACK, where A is the top element and B isthe next- to-top
element.
b) Evaluate B Ө A.
c) Push the result of (b) back on STACK
[End of If structure]
[End of step2 loop]
Step 5: Set VALUE equal to top element on STACK. Step 6:
Return(VALUE)
Step 7: Exit.

EXAMPLE: Consider the following postfix expression: P: 5,


6, 2, +, *, 12, 4, /, -

Symbol Scanned STACK


(1) 5 5
(2) 6 5, 6
(3) 2 5, 6, 2
(4) + 5, 8
(5) * 40
(6) 12 40, 12
(7) 4 40, 12, 4
(8) / 40, 3
(9) - 37
(10) )

The result of this postfix expression is 37.

24
QUEUE ADT
Queue is a linear data structure used in various applications of computer science. Like people stand
in a queue to get a particular service, various processes will wait in a queue for their turn to avail a
service.
Queue is a linear list in which insertions takes place at one end called the rear or tail of the
queue and deletions at the other end called as front or head of the queue.

When an element is to join the queue, it is inserted at the rear end of the queue and when an element is
to be deleted, the one at the front end of the queue is deleted automatically.
In queues always the first inserted element will be the first to be deleted. That‟s why it is also
called as FIFO – First-in First-Out data structure (or FCFS – First Come First Serve data structure)

APPLICATIONS OF QUEUE
□ CPU Scheduling (Round Robin Algorithm)
□ Printer Spooling
□ Tree & Graph Traversals
□ Palindrome Checker
□ Undo & Redo Operations in some Software‟s

OPERATIONS ON QUEUE
The queue data structure supports two operations:
Enqueue: Inserting an element into the queue is called enqueuing the queue. After the data have
been inserted into the queue, the new element becomes the rear.
Dequeue: Deleting an element from the queue is called dequeuing the queue. The data at the front of
the queue are returned to the user and removed from the queue.

IMPLEMENTATION OF QUEUES
Queues can be implemented or represented in memory in two ways:
1. Using Arrays (Static Implementation).
2. Using Linked Lists (Dynamic Implementation).
2.6.1.1 Implementation of Queue Us ing Arrays
A common method of implementing a queue data structure is to use another sequential data
structure, viz, arrays. With this representation, two pointers namely, Front and Rear are used to
indicate two ends of the queue. For insertion of next element, pointer Rear will be adjusted and for
deletion pointer Front will be adjusted.

25
However, the array implementation puts a limitation on the capacity of the queue. The number
of elements in the queue cannot exceed the maximum dimension of the one dimensional array.
Thus a queue that is accommodated in an array Q[1:n], cannot hold more than n elements.
Hence every insertion of an element into the queue has to necessarily test for a QUEUE
FULL condition before executing the insertion operation. Again, each deletion has to ensure
that it is not attempted on a queue which is already empty calling for the need to test for a
QUEUE EMPTY condition before executing the deletion operation.

Algorithm of insert operation on a queue


Procedure INSERTQ (Q, n, ITEM, REAR)
// this procedure inserts an element ITEM into Queue with capacity n
Step 1: if(REAR=n ) then
Write:“QUEUE_FULL” and Exit
Step 2: REAR=REAR + 1 //Increment REAR
Step 3: Q[REAR]= ITEM //Insert ITEM as the rear
element Step 4: Exit
It can be observed that addition of every new element into the queue increments the REAR
variable. However, before insertion, the condition whether the queue is full is checked

Algorithm of delete operation on a queue


Procedure DELETEQ (Q, FRONT, REAR, ITEM)
Step 1: If (FRONT >REAR) then:

Write: “QUEUE EMPTY” and

Exit. Step 2: ITEM = Q[FRONT]


Step 3: FRONT =FRONT + 1
Step 4: Exit.
To perform delete operation, the participation of both the variables FRONT and REAR is
essential. Before deletion, the condition FRONT =REAR checks for the emptiness of the
queue. If the queue is not empty, the element is removed through ITEM and subsequently
FRONT is incremented by 1.

26

You might also like