SlideShare a Scribd company logo
LIST DATA STRUCTURE
LISTS:
• A list is a data structure that stores a collection of elements in
a sequence.
• A list is an ordered data structure with elements separated by
a comma and enclosed within square brackets.
• Lists can be used to store any type of data, such as numbers,
strings, objects, or even other lists.
• Lists are one of the most common data structures in computer
science, and they are used in a wide variety of applications.
• The list can also be defined as an abstract data type in which
the elements are stored in an ordered manner for easier and
efficient retrieval of the elements.
• List Data Structure allows repetition that means a single
piece of data can occur more than once in a list.
• In the case of multiple entries of the same data, each entry
of that repeating data is considered as a distinct item or
entry.
• It is very much similar to the array but the major difference
between the array and the list data structure is that array
stores only homogenous data in them whereas the list (in
some programming languages) can store heterogeneous
data items.
• List Data Structure is also known as a sequence.
The list can be called Dynamic size arrays, which means their
size increase as we go on adding data in them and we need
not to pre-define a static size for the list.
• For example,
1.numbers = [ 1, 2, 3, 4, 5]
From example1, 'numbers' is the name of the List Data
Structure and it has five items stored in it, all numeric type.
Whenever we want to access any element from this list, we
use indexing system which starts from zero to n-1, where n is
the size of the list.
2. mixed_data = [205, 'Nirnay', 8.56]
From example2, mixed_data is the name of the list that stores
the data of different types. (integer, string and float data type)
We can add more data to these defined List and that
will get appended at the last of the list.
•For example,
If we add another data in the mixed_data list, it will get
appended after the float value object having value
'8.56’.
We can also add repeating values to these list-objects.
Various operations on the List Data Structure:
• Add or Insert Operation:
In Add or Insert operation, a new item (of any data type) is added in the
List Data Structure or Sequence object.
• Replace or reassign Operation:
In Replace or reassign operation, the already existing value in the List
object is changed or modified. In other words, a new value is added at that
particular index of the already existing value.
• Delete or remove Operation:
In the Delete or remove operation, the already present element is deleted
or removed from the Dictionary or associative array object.
• Find or Lookup or Search Operation:
In the Find or Lookup operation, the element stored in that List Data
Structure or Sequence object is fetched.
Examples:
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
• A single element can be added using an append function.
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
Advantages of List:
• Efficiency:
Lists are very efficient for storing and retrieving data.
This is because they are implemented as dynamic arrays,
which means that the computer can access them quickly and
easily.
• Simplicity:
Lists are a very simple data structure to understand and use.
• Versatility:
Lists can be used to store a wide variety of data types and can
be used to implement many different algorithms.
How lists are used in real-world applications:
• Games:
Lists are used to store game objects, such as characters, enemies and
projectiles.
• Image processing:
Lists are used to store images and to perform various image processing
operations, such as filtering and convolution.
• Machine learning:
Lists are used to store data and to train and deploy machine learning
models.
• Scientific computing:
Lists are used to store and manipulate data in scientific applications,
such as simulations and numerical analysis.
STACK DATA STRUCTURE
STACKS:
•Stacks in Data Structures is a linear type of data
structure that follows the LIFO (Last-In-First-Out)
principle and allows insertion and deletion operations
from one end of the stack data structure, that is top.
• Implementation of the stack can be done by
contiguous memory which is an array, and non-
contiguous memory which is a linked list.
•Stack plays a vital role in many applications.
•Real-life examples of a stack are a deck of cards, piles
of books, piles of money, and many more.
Some key points related to stack:
•It is called as stack because it behaves like a real-world
stack, piles of books, etc.
•A Stack is an abstract data type with a pre-defined
capacity, which means that it can store the elements
of a limited size.
•It is a data structure that follows some order to insert
and delete the elements, and that order can be LIFO
(LAST IN FIRST OUT) or FILO (FIRST IN LAST OUT).
Working of Stack:
• Stack works on the LIFO pattern.
• Inserting a new element in the stack is termed a push operation.
• Removing or deleting elements from the stack is termed pop
operation
Standard Stack Operations:
• push (): When we insert an element in a stack then the operation is
known as a push. If the stack is full then the overflow condition
occurs.
• pop (): When we delete an element from the stack, the operation is
known as a pop. If the stack is empty means that no element exists in
the stack, this state is known as an underflow state.
• is Empty (): It determines whether the stack is empty or not.
• Is Full (): It determines whether the stack is full or not.'
• peek (): It returns the element at the given position.
• count (): It returns the total number of elements available in a stack.
• change (): It changes the element at the given position.
• display (): It prints all the elements available in the stack.
PUSH operation:
The steps involved in the PUSH operation is given below:
• Before inserting an element in a stack, we check whether the stack is
full.
• If we try to insert the element in a stack, and the stack is full, then the
overflow condition occurs.
• When we initialize a stack, we set the value of top as -1 to check that
the stack is empty.
• When the new element is pushed in a stack, first, the value of the top
gets incremented, i.e., top=top+1, and the element will be placed at
the new position of the top.
• The elements will be inserted until we reach the max size of the stack.
Push operation includes various
steps:
•Step 1: First, check whether or not the stack
is full
•Step 2: If the stack is complete, then exit
•Step 3: If not, increment the top by one
•Step 4: Insert a new element where the top
is pointing
•Step 5: Success
The algorithm of the push operation is:
Begin push: stack, item
If the stack is complete(Full), return null
end if
top ->top+1;
stack[top] <- item
end
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
POP operation:
The steps involved in the POP operation is given below:
•Before deleting the element from the stack, we
check whether the stack is empty.
•If we try to delete the element from the empty
stack, then the underflow condition occurs.
•If the stack is not empty, we first access the
element which is pointed by the top
•Once the pop operation is performed, the top is
decremented by 1, i.e., top=top-1.
Pop operation includes various steps:
•Step 1: First, check whether or not the stack is
empty
•Step 2: If the stack is empty, then exit
•Step 3: If not, access the topmost data element
•Step 4: Decrement the top by one
•Step 5: Success
The algorithm of the pop operation:
Begin pop: stack
if the stack is empty
return null
end if
item -> stack[top] ;
Top -> top - 1;
Return item;
end
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
Peek Operation:
The algorithm of a peek operation is:
begin to peek
return stack[top];
End
The implementation of the peek operation is:
int peek()
{
return stack[top];
}
The algorithm of the isEmpty() function:
begin
if
topless than 1
return true
else
return false
else if
end
Types of Stacks:
• Register Stack:
This type of stack is also a memory element present in the
memory unit and can handle a small amount of data only.
The height of the register stack is always limited as the size of
the register stack is very small compared to the memory.
• Memory Stack:
This type of stack can handle a large amount of memory data.
The height of the memory stack is flexible as it occupies a
large amount of memory data.
Implementation of Stack:
There are two ways to implement a stack
• Using array
• Using linked list
Implementing Stack using Arrays:
• In array implementation, the stack is formed using an array. All the
operations are performed using arrays.
program to implement basic stack operations:
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stackn";
return true;
}
}
}
int Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
}
Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functionsint main ()
{
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stackn";
//print top element of stack after poping
cout << "Top element is: " << s.peek() << endl;
//print all elements in stack:
cout <<"Elements present in stack: ";
while(!s.isEmpty())
{
// print top element in stack
cout << s.peek() <<" ";
// remove top element in stack
s.pop();
}
return 0;
}
Output:
10 pushed into stack
20 pushed into stack
30 pushed into stack
30 Popped from stack
Top element is: 20
Elements present in stack: 20 10
Advantages of array implementation:
•Easy to implement.
•Memory is saved as pointers are not involved.
Disadvantages of array implementation:
•It is not dynamic.
•It doesn’t grow and shrink depending on needs
at runtime.
Implementing Stack using Linked List:
•Every new element is inserted as a top element
in the linked list implementation of stacks in data
structures.
•That means every newly inserted element is
pointed to the top.
•Whenever you want to remove an element from
the stack, remove the node indicated by the top,
by moving the top to its previous node in the list.
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
Program for linked list implementation of stack:
#include <bits/stdc++.h>
using namespace std;
// A structure to represent a stack
class StackNode {
public:
int data;
StackNode* next;
};
StackNode* newNode(int data)
{
StackNode* stackNode = new StackNode();
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(StackNode* root)
{
return !root;
}
void push(StackNode** root, int data)
{
StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
cout << data << " pushed to stackn";
}
int pop(StackNode** root)
{
if (isEmpty(*root))
return INT_MIN;
StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}
int peek(StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}
// Driver code
int main()
{
StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
cout << pop(&root) << " popped from stackn";
cout << "Top element is " << peek(root) << endl;
cout <<"Elements present in stack : ";
//print all elements in stack :
while(!isEmpty(root))
{
// print top element in stack
cout << peek(root) <<" ";
// remove top element in stack
pop(&root);
}
return 0;
}
Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
30 popped from stack
Top element is 20
Elements present in stack : 20 10
Advantages of Linked List implementation:
• The linked list implementation of a stack can grow and shrink
according to the needs at runtime.
• It is used in many virtual machines like JVM.
• Stacks are more secure and reliable as they do not get corrupted
easily.
• Stack cleans up the objects automatically.
Disadvantages of Linked List implementation:
• Requires extra memory due to the involvement of pointers.
• Random accessing is not possible in stack.
• The total size of the stack must be defined before.
• If the stack falls outside the memory it can lead to abnormal
termination.
Application of Stack in Data Structures:
• Function calls:
When a function is called, its arguments are pushed onto a stack.
When the function returns, its arguments are popped off the
stack.
This allows the caller of the function to resume execution where it
left off.
• Expression evaluation:
When a compiler evaluates an expression, it pushes the operands
onto a stack.
When the compiler encounters an operator, it pops the two top
operands off the stack and performs the operation.
The result of the operation is then pushed back onto the stack.
• Undo/redo:
Many software applications use stacks to implement undo/redo
functionality.
When a user performs an action, the application pushes the state of
the application onto a stack.
When the user wants to undo the action, the application pops the
previous state off the stack and restores the application to that state.
• Expression Conversion
• Backtracking
• Parentheses Checking
• String Reversal
• Syntax Parsing
• Memory Management
FRAME DATA STRUCTURE
FRAMES:
• A frame data structure is a data structure that stores a collection of
related data items in a single unit.
• Frames are typically used to represent objects or entities in a
computer program.
• For example, a frame might be used to represent a customer in a
customer relationship management (CRM) system, or a product in an e-
commerce system.
• Frames are typically implemented as key-value pairs, where the key is a
unique identifier for the data item and the value is the data item itself.
• Frames can also be nested, meaning that a frame can contain other
frames.
• This allows us to represent complex objects and relationships between
objects.
• A data frame is a table or a two-dimensional array-like
structure in which each column contains values of one variable
and each row contains one set of values from each column.
• A DataFrame is a data structure that organizes data into a 2-
dimensional table of rows and columns, much like a
spreadsheet.
• DataFrames are one of the most common data structures
used in modern data analytics because they are a flexible and
intuitive way of storing and working with data.
• Every DataFrame contains a blueprint, known as a schema,
that defines the name and data type of each column.
• Missing or incomplete values are stored as null values in the
DataFrame.
•A simple analogy is that a DataFrame is like a
spreadsheet with named columns.
•However, the difference between them is that while a
spreadsheet sits on one computer in one specific
location, a DataFrame can span thousands of
computers.
•In this way, DataFrames make it possible to do analytics
on big data, using distributed computing clusters.
•The reason for putting the data on more than one
computer should be intuitive: either the data is too
large to fit on one machine or it would simply take too
long to perform that computation on one machine.
• The concept of a DataFrame is common across many different
languages and frameworks.
• Data Frames are the main data type used in pandas, the popular
Python data analysis library, and DataFrames are also used in R, Scala,
and other languages.
characteristics of a data frame:
•The column names should be non-empty.
•The row names should be unique.
•The data stored in a data frame can be of
numeric, factor or character type.
•Each column should contain same number of
data items.
Advantages of Frames:
• Frames are very efficient for storing and retrieving data.
This is because frames are stored in a contiguous block of
memory, which means that the computer can access them
quickly and easily.
• Another advantage of frames is that they are very flexible
and extensible.
Frames can be easily modified to add new data items or to
change the structure of the data.
This makes frames well-suited for representing complex
objects and relationships between objects.
Application of Frames:
• Object-oriented programming:
Frames are often used to represent objects in object-oriented programming
languages.
For example, the following Python code shows how to define a frame to represent a
customer in a CRM system:
class Customer:
def __init__(self, name, email, phone_number):
self.name = name
self.email = email
self.phone_number = phone_number
# Create a new customer frame
customer_frame = Customer ("John Doe", "john.doe@example.com", "123-456-
7890")
•Artificial intelligence:
Frames are often used in artificial intelligence to
represent knowledge about the world.
For example, a frame might be used to represent the
concept of a "person" or the concept of a "chair."
•Database systems:
Frames can also be used to represent data in database
systems.
For example, a frame might be used to represent a row
in a table.

More Related Content

Similar to DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2 (20)

PPTX
data structures with algorithms vtu 2023 notes.pptx
hemanthkumar40680
 
PPTX
01-Introduction of DSA-1.pptx
DwijBaxi
 
PDF
notes.pdf
ssuserd14cca
 
PPTX
Stack and queue power point presentation data structure and algorithms Stack-...
abhaysingh19149
 
PPTX
stacks and queues for public
iqbalphy1
 
PPTX
Stacks and Queue,Concept of Stack,LIFO,Fifo,
shaikhdaniyal8603
 
PPTX
DSEC1.pptx stack exchange communities that I am not đźš­ hi nahi
ganesh209832
 
PPT
Stack a Data Structure
ForwardBlog Enewzletter
 
PPT
unit 5 stack & queue.ppt
SeethaDinesh
 
PDF
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Balwant Gorad
 
PPTX
1.Introduction to Data Structures and Algorithms.pptx
BlueSwede
 
PDF
Chapter 4 stack
jadhav_priti
 
PPT
Data Structures
Dr.Umadevi V
 
PPTX
My lecture stack_queue_operation
Senthil Kumar
 
PPT
Stacks
sweta dargad
 
PPTX
Queues
nidhisatija1
 
PPT
Stack data structures with definition and code
bansidharj11
 
PPTX
stack_presentaton_HUSNAIN[2].pojklklklptx
HusnainNaqvi2
 
PPT
Difference between stack and queue
Pulkitmodi1998
 
data structures with algorithms vtu 2023 notes.pptx
hemanthkumar40680
 
01-Introduction of DSA-1.pptx
DwijBaxi
 
notes.pdf
ssuserd14cca
 
Stack and queue power point presentation data structure and algorithms Stack-...
abhaysingh19149
 
stacks and queues for public
iqbalphy1
 
Stacks and Queue,Concept of Stack,LIFO,Fifo,
shaikhdaniyal8603
 
DSEC1.pptx stack exchange communities that I am not đźš­ hi nahi
ganesh209832
 
Stack a Data Structure
ForwardBlog Enewzletter
 
unit 5 stack & queue.ppt
SeethaDinesh
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Balwant Gorad
 
1.Introduction to Data Structures and Algorithms.pptx
BlueSwede
 
Chapter 4 stack
jadhav_priti
 
Data Structures
Dr.Umadevi V
 
My lecture stack_queue_operation
Senthil Kumar
 
Stacks
sweta dargad
 
Queues
nidhisatija1
 
Stack data structures with definition and code
bansidharj11
 
stack_presentaton_HUSNAIN[2].pojklklklptx
HusnainNaqvi2
 
Difference between stack and queue
Pulkitmodi1998
 

Recently uploaded (20)

PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Horarios de distribuciĂłn de agua en julio
pegazohn1978
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Horarios de distribuciĂłn de agua en julio
pegazohn1978
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Ad

DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2

  • 2. LISTS: • A list is a data structure that stores a collection of elements in a sequence. • A list is an ordered data structure with elements separated by a comma and enclosed within square brackets. • Lists can be used to store any type of data, such as numbers, strings, objects, or even other lists. • Lists are one of the most common data structures in computer science, and they are used in a wide variety of applications. • The list can also be defined as an abstract data type in which the elements are stored in an ordered manner for easier and efficient retrieval of the elements.
  • 3. • List Data Structure allows repetition that means a single piece of data can occur more than once in a list. • In the case of multiple entries of the same data, each entry of that repeating data is considered as a distinct item or entry. • It is very much similar to the array but the major difference between the array and the list data structure is that array stores only homogenous data in them whereas the list (in some programming languages) can store heterogeneous data items. • List Data Structure is also known as a sequence.
  • 4. The list can be called Dynamic size arrays, which means their size increase as we go on adding data in them and we need not to pre-define a static size for the list. • For example, 1.numbers = [ 1, 2, 3, 4, 5] From example1, 'numbers' is the name of the List Data Structure and it has five items stored in it, all numeric type. Whenever we want to access any element from this list, we use indexing system which starts from zero to n-1, where n is the size of the list. 2. mixed_data = [205, 'Nirnay', 8.56] From example2, mixed_data is the name of the list that stores the data of different types. (integer, string and float data type)
  • 5. We can add more data to these defined List and that will get appended at the last of the list. •For example, If we add another data in the mixed_data list, it will get appended after the float value object having value '8.56’. We can also add repeating values to these list-objects.
  • 6. Various operations on the List Data Structure: • Add or Insert Operation: In Add or Insert operation, a new item (of any data type) is added in the List Data Structure or Sequence object. • Replace or reassign Operation: In Replace or reassign operation, the already existing value in the List object is changed or modified. In other words, a new value is added at that particular index of the already existing value. • Delete or remove Operation: In the Delete or remove operation, the already present element is deleted or removed from the Dictionary or associative array object. • Find or Lookup or Search Operation: In the Find or Lookup operation, the element stored in that List Data Structure or Sequence object is fetched.
  • 9. • A single element can be added using an append function.
  • 15. Advantages of List: • Efficiency: Lists are very efficient for storing and retrieving data. This is because they are implemented as dynamic arrays, which means that the computer can access them quickly and easily. • Simplicity: Lists are a very simple data structure to understand and use. • Versatility: Lists can be used to store a wide variety of data types and can be used to implement many different algorithms.
  • 16. How lists are used in real-world applications: • Games: Lists are used to store game objects, such as characters, enemies and projectiles. • Image processing: Lists are used to store images and to perform various image processing operations, such as filtering and convolution. • Machine learning: Lists are used to store data and to train and deploy machine learning models. • Scientific computing: Lists are used to store and manipulate data in scientific applications, such as simulations and numerical analysis.
  • 18. STACKS: •Stacks in Data Structures is a linear type of data structure that follows the LIFO (Last-In-First-Out) principle and allows insertion and deletion operations from one end of the stack data structure, that is top. • Implementation of the stack can be done by contiguous memory which is an array, and non- contiguous memory which is a linked list. •Stack plays a vital role in many applications. •Real-life examples of a stack are a deck of cards, piles of books, piles of money, and many more.
  • 19. Some key points related to stack: •It is called as stack because it behaves like a real-world stack, piles of books, etc. •A Stack is an abstract data type with a pre-defined capacity, which means that it can store the elements of a limited size. •It is a data structure that follows some order to insert and delete the elements, and that order can be LIFO (LAST IN FIRST OUT) or FILO (FIRST IN LAST OUT).
  • 20. Working of Stack: • Stack works on the LIFO pattern. • Inserting a new element in the stack is termed a push operation. • Removing or deleting elements from the stack is termed pop operation
  • 21. Standard Stack Operations: • push (): When we insert an element in a stack then the operation is known as a push. If the stack is full then the overflow condition occurs. • pop (): When we delete an element from the stack, the operation is known as a pop. If the stack is empty means that no element exists in the stack, this state is known as an underflow state. • is Empty (): It determines whether the stack is empty or not. • Is Full (): It determines whether the stack is full or not.' • peek (): It returns the element at the given position. • count (): It returns the total number of elements available in a stack. • change (): It changes the element at the given position. • display (): It prints all the elements available in the stack.
  • 22. PUSH operation: The steps involved in the PUSH operation is given below: • Before inserting an element in a stack, we check whether the stack is full. • If we try to insert the element in a stack, and the stack is full, then the overflow condition occurs. • When we initialize a stack, we set the value of top as -1 to check that the stack is empty. • When the new element is pushed in a stack, first, the value of the top gets incremented, i.e., top=top+1, and the element will be placed at the new position of the top. • The elements will be inserted until we reach the max size of the stack.
  • 23. Push operation includes various steps: •Step 1: First, check whether or not the stack is full •Step 2: If the stack is complete, then exit •Step 3: If not, increment the top by one •Step 4: Insert a new element where the top is pointing •Step 5: Success
  • 24. The algorithm of the push operation is: Begin push: stack, item If the stack is complete(Full), return null end if top ->top+1; stack[top] <- item end
  • 26. POP operation: The steps involved in the POP operation is given below: •Before deleting the element from the stack, we check whether the stack is empty. •If we try to delete the element from the empty stack, then the underflow condition occurs. •If the stack is not empty, we first access the element which is pointed by the top •Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
  • 27. Pop operation includes various steps: •Step 1: First, check whether or not the stack is empty •Step 2: If the stack is empty, then exit •Step 3: If not, access the topmost data element •Step 4: Decrement the top by one •Step 5: Success
  • 28. The algorithm of the pop operation: Begin pop: stack if the stack is empty return null end if item -> stack[top] ; Top -> top - 1; Return item; end
  • 30. Peek Operation: The algorithm of a peek operation is: begin to peek return stack[top]; End The implementation of the peek operation is: int peek() { return stack[top]; }
  • 31. The algorithm of the isEmpty() function: begin if topless than 1 return true else return false else if end
  • 32. Types of Stacks: • Register Stack: This type of stack is also a memory element present in the memory unit and can handle a small amount of data only. The height of the register stack is always limited as the size of the register stack is very small compared to the memory. • Memory Stack: This type of stack can handle a large amount of memory data. The height of the memory stack is flexible as it occupies a large amount of memory data.
  • 33. Implementation of Stack: There are two ways to implement a stack • Using array • Using linked list Implementing Stack using Arrays: • In array implementation, the stack is formed using an array. All the operations are performed using arrays.
  • 34. program to implement basic stack operations: #include <bits/stdc++.h> using namespace std; #define MAX 1000 class Stack { int top; public: int a[MAX]; // Maximum size of Stack Stack() { top = -1; } bool push(int x); int pop(); int peek(); bool isEmpty(); };
  • 35. bool Stack::push(int x) { if (top >= (MAX - 1)) { cout << "Stack Overflow"; return false; } else { a[++top] = x; cout << x << " pushed into stackn"; return true; } } }
  • 36. int Stack::pop() { if (top < 0) { cout << "Stack Underflow"; return 0; } else { int x = a[top--]; return x; } }
  • 37. Stack::peek() { if (top < 0) { cout << "Stack is Empty"; return 0; } else { int x = a[top]; return x; } }
  • 38. bool Stack::isEmpty() { return (top < 0); } // Driver program to test above functionsint main () { class Stack s; s.push(10); s.push(20); s.push(30);
  • 39. cout << s.pop() << " Popped from stackn"; //print top element of stack after poping cout << "Top element is: " << s.peek() << endl; //print all elements in stack: cout <<"Elements present in stack: "; while(!s.isEmpty()) { // print top element in stack cout << s.peek() <<" "; // remove top element in stack s.pop(); } return 0; }
  • 40. Output: 10 pushed into stack 20 pushed into stack 30 pushed into stack 30 Popped from stack Top element is: 20 Elements present in stack: 20 10
  • 41. Advantages of array implementation: •Easy to implement. •Memory is saved as pointers are not involved. Disadvantages of array implementation: •It is not dynamic. •It doesn’t grow and shrink depending on needs at runtime.
  • 42. Implementing Stack using Linked List: •Every new element is inserted as a top element in the linked list implementation of stacks in data structures. •That means every newly inserted element is pointed to the top. •Whenever you want to remove an element from the stack, remove the node indicated by the top, by moving the top to its previous node in the list.
  • 44. Program for linked list implementation of stack: #include <bits/stdc++.h> using namespace std; // A structure to represent a stack class StackNode { public: int data; StackNode* next; }; StackNode* newNode(int data) { StackNode* stackNode = new StackNode(); stackNode->data = data; stackNode->next = NULL; return stackNode; }
  • 45. int isEmpty(StackNode* root) { return !root; } void push(StackNode** root, int data) { StackNode* stackNode = newNode(data); stackNode->next = *root; *root = stackNode; cout << data << " pushed to stackn"; }
  • 46. int pop(StackNode** root) { if (isEmpty(*root)) return INT_MIN; StackNode* temp = *root; *root = (*root)->next; int popped = temp->data; free(temp); return popped; }
  • 47. int peek(StackNode* root) { if (isEmpty(root)) return INT_MIN; return root->data; } // Driver code int main() { StackNode* root = NULL; push(&root, 10); push(&root, 20); push(&root, 30);
  • 48. cout << pop(&root) << " popped from stackn"; cout << "Top element is " << peek(root) << endl; cout <<"Elements present in stack : "; //print all elements in stack : while(!isEmpty(root)) { // print top element in stack cout << peek(root) <<" "; // remove top element in stack pop(&root); } return 0; }
  • 49. Output: 10 pushed to stack 20 pushed to stack 30 pushed to stack 30 popped from stack Top element is 20 Elements present in stack : 20 10
  • 50. Advantages of Linked List implementation: • The linked list implementation of a stack can grow and shrink according to the needs at runtime. • It is used in many virtual machines like JVM. • Stacks are more secure and reliable as they do not get corrupted easily. • Stack cleans up the objects automatically. Disadvantages of Linked List implementation: • Requires extra memory due to the involvement of pointers. • Random accessing is not possible in stack. • The total size of the stack must be defined before. • If the stack falls outside the memory it can lead to abnormal termination.
  • 51. Application of Stack in Data Structures: • Function calls: When a function is called, its arguments are pushed onto a stack. When the function returns, its arguments are popped off the stack. This allows the caller of the function to resume execution where it left off. • Expression evaluation: When a compiler evaluates an expression, it pushes the operands onto a stack. When the compiler encounters an operator, it pops the two top operands off the stack and performs the operation. The result of the operation is then pushed back onto the stack.
  • 52. • Undo/redo: Many software applications use stacks to implement undo/redo functionality. When a user performs an action, the application pushes the state of the application onto a stack. When the user wants to undo the action, the application pops the previous state off the stack and restores the application to that state. • Expression Conversion • Backtracking • Parentheses Checking • String Reversal • Syntax Parsing • Memory Management
  • 54. FRAMES: • A frame data structure is a data structure that stores a collection of related data items in a single unit. • Frames are typically used to represent objects or entities in a computer program. • For example, a frame might be used to represent a customer in a customer relationship management (CRM) system, or a product in an e- commerce system. • Frames are typically implemented as key-value pairs, where the key is a unique identifier for the data item and the value is the data item itself. • Frames can also be nested, meaning that a frame can contain other frames. • This allows us to represent complex objects and relationships between objects.
  • 55. • A data frame is a table or a two-dimensional array-like structure in which each column contains values of one variable and each row contains one set of values from each column. • A DataFrame is a data structure that organizes data into a 2- dimensional table of rows and columns, much like a spreadsheet. • DataFrames are one of the most common data structures used in modern data analytics because they are a flexible and intuitive way of storing and working with data. • Every DataFrame contains a blueprint, known as a schema, that defines the name and data type of each column. • Missing or incomplete values are stored as null values in the DataFrame.
  • 56. •A simple analogy is that a DataFrame is like a spreadsheet with named columns. •However, the difference between them is that while a spreadsheet sits on one computer in one specific location, a DataFrame can span thousands of computers. •In this way, DataFrames make it possible to do analytics on big data, using distributed computing clusters. •The reason for putting the data on more than one computer should be intuitive: either the data is too large to fit on one machine or it would simply take too long to perform that computation on one machine.
  • 57. • The concept of a DataFrame is common across many different languages and frameworks. • Data Frames are the main data type used in pandas, the popular Python data analysis library, and DataFrames are also used in R, Scala, and other languages.
  • 58. characteristics of a data frame: •The column names should be non-empty. •The row names should be unique. •The data stored in a data frame can be of numeric, factor or character type. •Each column should contain same number of data items.
  • 59. Advantages of Frames: • Frames are very efficient for storing and retrieving data. This is because frames are stored in a contiguous block of memory, which means that the computer can access them quickly and easily. • Another advantage of frames is that they are very flexible and extensible. Frames can be easily modified to add new data items or to change the structure of the data. This makes frames well-suited for representing complex objects and relationships between objects.
  • 60. Application of Frames: • Object-oriented programming: Frames are often used to represent objects in object-oriented programming languages. For example, the following Python code shows how to define a frame to represent a customer in a CRM system: class Customer: def __init__(self, name, email, phone_number): self.name = name self.email = email self.phone_number = phone_number # Create a new customer frame customer_frame = Customer ("John Doe", "[email protected]", "123-456- 7890")
  • 61. •Artificial intelligence: Frames are often used in artificial intelligence to represent knowledge about the world. For example, a frame might be used to represent the concept of a "person" or the concept of a "chair." •Database systems: Frames can also be used to represent data in database systems. For example, a frame might be used to represent a row in a table.