SlideShare a Scribd company logo
Data Structures
Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423603
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified
Department of Information Technology
(NBAAccredited)
Ms. K. D. Patil
Assistant Professor
Linked Organization
• Introduction, References and Basic Types, Linked list ADT,
Implementing Singly linked list, Doubly linked lists, Implementing
Doubly linked list, Implementation of stack using Linked organization,
Applications: well formed-ness of parenthesis, Implementation of
queue using linked organization, cloning Data Structures, Linked list
efficiency
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
Learning Outcomes
• At the end of this unit, student will able to-
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• The major problem with the stack implemented using an array is, it works only for a fixed
number of data values
• That means the amount of data must be specified at the beginning of the implementation
itself
• Stack implemented using an array is not suitable, when we don't know the size of data which
we are going to use
• The stack implemented using linked list can work for an unlimited number of values
• That means, stack implemented using linked list works for the variable size of data
• So, there is no need to fix the size at the beginning of the implementation
• The Stack implemented using linked list can organize as many data values as we want.
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• In linked list implementation of a stack, every new element is
inserted as 'top' element.
• That means every newly inserted element is pointed by 'top'.
• Whenever we want to remove an element from the stack, simply
remove the node which is pointed by 'top' by moving 'top' to its
previous node in the list.
• The next field of the first element must be always NULL.
• Here, the last inserted node is 99 and the first inserted node is 25.
The order of elements inserted is 25, 32,50 and 99.
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Push() Operation: Insertion at the beginning
• Use the following steps to insert a new node into the stack.
• Step 1 - Create a newNode with given value and allocate memory to it
• Step 2 - Check whether stack is Empty (top == NULL)
• Step 3 - If it is Empty, then set newNode → next = NULL. (This is the first node in
the list, head)
• Step 4 - If there are some nodes in the list already, then we have to add the new
element in the beginning of the list (head position). For that, assign the address of
the starting element, head to the address field of the new node and make the new
node, top of the list (this is new head of the list now).
• If it is Not Empty, then set newNode → next = top.
• Step 5 - Finally, set top = newNode.
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Push() Operation: Insertion at the beginning
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Pop() Operation: Deletion at the beginning
• Use the following steps to delete a node from the stack.
• Step 1 - Check whether stack is Empty (top == NULL).
• Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not
possible!!!" and terminate the function (An underflow condition will occur when
we try to pop an element when the Stack is already empty. )
• Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'. (In
stack, the elements are popped only from one end, therefore, the value stored in
the head pointer must be deleted)
• Step 4 - Then set 'top = top → next'. (The next node of the head node now
becomes the head node.)
• Step 5 - Finally, delete 'temp'. (free(temp)). (After deletion the node must be freed
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Pop() Operation: Deletion at the beginning
Stack using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Display() Operation:
• Use the following steps to delete a node from the stack.
• Step 1 - Check whether stack is Empty (top == NULL).
• Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
• Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize
with top. (Copy the head pointer into a temporary pointer)
• Step 4 - Display 'temp → data' and move it to the next node. Repeat the same
until temp reaches to the first node in the stack. (temp → next != NULL).
• Step 5 - Finally! Display 'temp → data ---> NULL'.
Time and Space Complexity of Stack Implementation
using Linked List
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• The time complexity for various methods is written below:
• push(): O(1) - as we are not traversing the whole list.
• pop(): O(1) - as we are not traversing the entire list.
• peek(): O(1) - as we are printing the head node
• isEmpty(): O(1) - as we are checking only the head node.
• display(): O(n) - As we are traversing through the whole list it will be O(n), where
n is the number of nodes present in the linked list
• Space Complexity for implementation of stack using linked list is O(n) for every
operation.
Advantages of Stack Implementation using Linked List
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Dynamic size:
• The size of the stack can be adjusted dynamically as the linked list can grow or
shrink according to the elements pushed or popped.
• Efficient memory utilization:
• The linked list uses only as much memory as required by the elements in the
stack, whereas an array-based implementation might have to allocate extra
memory to accommodate growth.
• Flexibility:
• Linked list implementation provides more flexibility than an array-based
implementation as elements can be added or removed anywhere in the list.
Advantages of Stack Implementation using Linked List
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Ease of implementation:
• Implementing a stack using linked list is easier as it only requires a few basic
operations to be performed on the linked list such as adding and removing
elements from the beginning.
• Improved performance:
• The linked list implementation can provide improved performance compared to
an array-based implementation, especially when dealing with large stacks, as
inserting or removing elements from the beginning of the linked list is an O(1)
operation.
Disadvantages of Stack Implementation using Linked List
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Increased memory usage:
• As each element in the stack is stored as a separate node, linked list
implementation of stack takes up more memory than other implementations
such as arrays.
• Slower performance:
• Operations on the linked list take more time compared to arrays, as accessing
elements in linked lists require traversing through multiple nodes.
• Complexity:
• Linked list implementation of the stack requires more complex coding compared
to other implementations such as arrays, leading to longer development time
and more bugs.
• Pointer management:
• Managing pointers in linked lists is more challenging compared to arrays, leading
to increased risk of bugs and data corruption.
Well formedness of Parenthesis (stack application)
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Given an expression string expression, examine whether the
pairs and the orders of “,“, “-”, “(“, “)”, “*“, “+” are correct in the
given expression.
• To test that, put all the opening brackets in the stack.
• Whenever you hit a closing bracket, search if the top of the
stack is the opening bracket of the same nature.
• If this holds then pop the stack and continue the iteration.
• In the end if the stack is empty, it means all brackets are
balanced or well-formed. Otherwise, they are not balanced.
Sample A
Input string: "{}[](){}{([{()}])}"
Output: expression is balanced
Sample B
Input string: "{}[]("
Output: expression is not balanced
Well formedness of Parenthesis (stack application)
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Follow the steps mentioned below to implement the idea:
• Declare a character stack (say temp).
• Now traverse the string exp.
• If the current character is a starting bracket ( ‘(‘ or ‘,‘ or ‘*‘ ) then push it to stack.
• If the current character is a closing bracket ( ‘)’ or ‘-’ or ‘+’ ) then pop from the stack
and if the popped character is the matching starting bracket then fine.
• Else brackets are Not Balanced.
• After complete traversal, if some starting brackets are left in the stack then the expression
is Not balanced, else Balanced.
Well formedness of Parenthesis (stack application)
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
import java.util.*;
public class BalancedBrackets
{
static boolean areBracketsBalanced(String expr)
{
Deque<Character> stack = new ArrayDeque<Character>();
// Traversing the Expression
for (int i = 0; i < expr.length(); i++)
{
char x = expr.charAt(i);
if (x == '(' || x == '[' || x == '{')
{
// Push the element in the stack
stack.push(x);
continue;
}
Well formedness of Parenthesis (stack application)
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
// If current character is not opening bracket, then it must be
closing. So stack cannot be empty at this point.
if (stack.isEmpty())
return false;
char check;
switch (x) {
case ')':
check = stack.pop();
if (check == '{' || check == '[')
return false;
break;
case '}':
check = stack.pop();
if (check == '(' || check == '[')
return false;
break;
Well formedness of Parenthesis (stack application)
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
case ']':
check = stack.pop();
if (check == '(' || check == '{')
return false;
break;
}
}
return (stack.isEmpty()); // Check Empty Stack
}
public static void main(String[] args)
{
String expr = “,*()+-";
if (areBracketsBalanced(expr))
System.out.println("Balanced ");
else
System.out.println("Not Balanced ");
}
}
Queue using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• In a linked queue, each node of the queue consists of two fields, i.e., data field and
reference field.
• Each entity of the linked queue points to its immediate next entity in the memory.
• To keep track of the front and rear node, two pointers are preserved in the memory.
• The first pointer stores the location where the queue starts.
• Another pointer keeps track of the last data element of a queue.
Queue using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• enQueue(value) Operation: Insertion at the end
• We can use the following steps to insert a new node into the queue.
• The insertion in a linked queue is performed at the rear end by updating the
address value of the previous node where a rear pointer is pointing.
• Step 1 - Create a newNode with given value and set 'newNode → next' to NULL.
• Step 2 - Check whether queue is Empty (rear == NULL)
• Step 3 - If it is Empty then, set front = newNode and rear = newNode.
• Step 4 - If it is Not Empty then, set rear → next = newNode and rear = newNode.
Queue using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• enQueue(value) Operation: Insertion at the end
Queue using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• deQueue() Operation: deletion at the beginning
• We can use the following steps to delete a node from the queue.
• Step 1 - Check whether queue is Empty (front == NULL).
• Step 2 - If it is Empty, then display "Queue is Empty!!! Deletion is not
possible!!!" and terminate from the function
• Step 3 - If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
• Step 4 - Then set 'front = front → next' and delete 'temp' (free(temp)).
Queue using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• deQueue() Operation: deletion at the beginning
Queue using Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• display() Operation:
• We can use the following steps to display the queue.
• Step 1 - Check whether queue is Empty (front == NULL).
• Step 2 - If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
• Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize
with front.
• Step 4 - Display 'temp → data' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).
• Step 5 - Display 'temp → data ---> NULL'.
Time and Space Complexity of Queue Implementation
using Linked List
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• The time complexity for various methods is written below:
• enqueue(): O(1) – Best, O(n) – Average, Worst
• dequeue(): O(1) – Best, O(n) – Average, Worst
• isEmpty(): O(1)
• display(): O(n) – Best, O(n) – Average, Worst
Sequential Vs. Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
Sr. No. Linked Organization Sequential Organization
1. Data is stored in nodes that are linked together Data is stored in a linear sequence
2. Each node contains data and a pointer to the next node Each element is stored one after the other
3. Allows for fast insertions and deletions Allows for fast traversal and access
4. More complex to implement Simpler to implement
5.
Can be used for implementing data structures like
linked lists and trees
Can be used for implementing data structures like arrays
and stacks
6. Requires more memory for pointers Less memory is required as no pointers needed
7. Can be used for dynamic data structures Suitable for static data structures
8. Flexible in terms of size and structure Fixed-size and structure
9. Random access is not possible Random access is possible
Sequential Vs. Linked Organization
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
Sr. No. Linked Organization Sequential Organization
10.
Pointers may be pointing to null or non-existent
memory in case of broken links
All elements are stored in contiguous memory
11. Can have multiple pointers in case of bidirectional links Only one pointer is required to traverse the list
12. Can have a circular linked list Only a linear sequential list is possible
13. Can have multiple head and tail pointers Only one head and tail pointer is required
14. Can have variable length of data in each node Fixed length of data in each element
15.
Can be used for implementing more complex data
structures like graphs.
Can be used for simple data structures like queues and
stacks.
Cloning Data Structure
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Abstraction allows for a data structure to be treated as a single object, even though
the encapsulated implementation of the structure might rely on a more complex
combination of many objects.
• In a programming environment, a common expectation is that a copy of an object
has its own state and that, once made, the copy is independent of the original (for
example, so that changes to one do not directly affect the other).
• Cloning of Data Structures is defined as creating a duplicate or copy of an existing
data structure while maintaining its contents and structure.
Cloning Data Structure
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Depending on the Data Structures type, the cloning process can vary.
• Cloning allows you to work with the copy independently, making modifications
without affecting the original data structure.
• In java, the universal Object superclass defines a method named clone, which can
be used to produce what is known as a shallow copy of an object.
• This uses the standard assignment semantics to assign the value of each field of the
new object equal to the corresponding field of the existing object that is being
copied.
Cloning Data Structure
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• The reason this is known as a shallow copy is because if the field is a reference type,
then an initialization of the form duplicate.field = original.field causes the field of the
new object to refer to the same underlying instance as the field of the original object.
• A shallow copy is not always appropriate for all classes, and therefore, Java intentionally
disables use of the clone( ) method by declaring it as protected, and by having it throw a
CloneNotSupportedException when called.
• The author of a class must explicitly declare support for cloning by formally declaring
that the class implements the Cloneable interface, and by declaring a public version of
the clone( ) method.
Cloning Arrays
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Arrays support some special syntaxes such as a[k] and a.length
• But they are objects, and that array variables are reference variables.
• Example: consider the following code:
• The assignment of variable backup to data does not create any new array, it simply
creates a new alias for the same array.
Cloning Arrays
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• If we want to make a copy of the array, data, and assign a reference to the new array to
variable, backup, we should write:
backup = data.clone( );
• The clone method, when executed on an array, initializes each cell of the new array to
the value that is stored in the corresponding cell of the original array as follows.
Cloning Lists
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Clone() method of a class in Java is used to create a new instance of a class of the
current object and initialized all its fields with the contents of the specified object.
• To clone a list, one can iterate through the original list and use the clone method to copy
all the list elements and use the add method to append them to the list.
• Syntax:
protected Object clone()
throws CloneNotSupportedException
Cloning Lists
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• Steps:
• Create a cloneable class, which has the clone method overridden.
• Create a list of the class objects from an array using the asList method.
• Create an empty list.
• Loop through each element of the original list, and invoke the class object’s clone()
method (which returns the class instance) and use the add() method to append it to the
new list.
Cloning Lists
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Class needs to be cloneable
class sample implements Cloneable {
String username;
String msg;
sample (String username, String msg) // Constructor
{
this.username = username;
this.msg = msg;
}
public String toString() // To print the objects in the desired format
{
return "n" + username + "n" + msg + "n";
}
protected sample clone() // Overriding the inbuilt clone class
{
return new sample(username, msg);
}
}
// Program to clone a List in Java
class Example
{
public static void main(String[] args)
{
// Creating a list
List<sample> original = Arrays.asList (new sample(“Hello", “Students"));
// Creating an empty list
List<sample> cloned_list = new ArrayList<sample>();
// Looping through the list and cloning each element
for (sample temp : original)
cloned_list.add(temp.clone());
System.out.println(cloned_list);
}
}
Cloning stack
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• The clone() method of stack class is used to return a shallow copy of this Stack.
• It just creates a copy of the Stack.
• The copy will have a reference to a clone of the internal data array but not a reference
to the original internal data array.
• Syntax:
stack.clone()
Cloning stack
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>(); // Creating an empty Stack
stack.add("Welcome"); // Use add() method to add elements into the Stack
stack.add("To");
stack.add(“Data Structures Class");
System.out.println("Stack: " + stack); // Displaying the Stack
Object copy_Stack = stack.clone(); // Creating another Stack to copy
System.out.println("The cloned Stack is: " + copy_Stack); // Displaying the copy of Stack
}
}
References
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
• R. Lafore, “Data structures and Algorithms in Java”, Pearson education, ISBN: 9788
131718124.
• Michael Goodrich, Roberto Tamassia, Michael H. Goldwasser, “Data Structures and
Algorithms in Java”, 6th edition, wiley publication, ISBN: 978-1-118-77133-4
• R. Gilberg, B. Forouzan, “Data Structure: A Pseudo code approach with C++”, Cengage
Learning.
Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
Thank You!!!
Happy Learning!!!

More Related Content

PDF
Unit 1_SLL and DLL.pdf
PDF
Unit 1_Single Linked List and Double Linked List.pdf
PPT
Stack data structures with definition and code
PDF
computer notes - Stack
PPSX
Stacks fundamentals
PPT
Data Structures 3
PDF
Stacks
PPTX
stacks and queues
Unit 1_SLL and DLL.pdf
Unit 1_Single Linked List and Double Linked List.pdf
Stack data structures with definition and code
computer notes - Stack
Stacks fundamentals
Data Structures 3
Stacks
stacks and queues

Similar to Unit 1_Stack and Queue using Linked Organization.pdf (20)

PPTX
Data Structures and Agorithm: DS 06 Stack.pptx
PPTX
Data Structure.pptx
PPT
Exploring the Stack Stack operation.pptx
PPTX
The presentation on stack data structure
PPTX
DS-3asdfghjklxmmcnaefiuhavbifuhablc.pptx
DOCX
DSA- Unit III- STACK AND QUEUE
PPTX
Revisiting a data structures in detail with linked list stack and queue
PPTX
STACK, LINKED LIST ,AND QUEUE
PPT
Lecture 2c stacks
PDF
IRJET- Dynamic Implementation of Stack using Single Linked List
PPT
Linked list-stack-queue Data Structure .ppt
PPT
Operations on linked list
PPTX
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
PPTX
c programming and data structure notes for ECE
PPT
Data Structures and Discrete Mathematics
PDF
CS8391-DATA-STRUCTURES.pdf
PDF
CS8391-DATA STRUCTURE.pdf1111111111111111
PPTX
5.-Stacks.pptx
PPT
List Data Structure, Linked List, Stacks.ppt
PPTX
Data structure , stack , queue
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structure.pptx
Exploring the Stack Stack operation.pptx
The presentation on stack data structure
DS-3asdfghjklxmmcnaefiuhavbifuhablc.pptx
DSA- Unit III- STACK AND QUEUE
Revisiting a data structures in detail with linked list stack and queue
STACK, LINKED LIST ,AND QUEUE
Lecture 2c stacks
IRJET- Dynamic Implementation of Stack using Single Linked List
Linked list-stack-queue Data Structure .ppt
Operations on linked list
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
c programming and data structure notes for ECE
Data Structures and Discrete Mathematics
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA STRUCTURE.pdf1111111111111111
5.-Stacks.pptx
List Data Structure, Linked List, Stacks.ppt
Data structure , stack , queue
Ad

More from KanchanPatil34 (20)

PDF
Unit 1_Data Validation_Validation Techniques.pdf
PDF
Unit 1_Concet of Feature-Feature Selection Methods.pdf
PDF
Unit 1_Introduction to ML_Types_Applications.pdf
PDF
Unit 6_Cyber Laws Indian Act_Digital Signature.pdf
PDF
Unit 6_DoS and DDoS_SQL Injection_tools.pdf
PDF
Unit 6_keylogger_Spywares_virus_worms.pdf
PDF
Unit 6_Introduction_Phishing_Password Cracking.pdf
PDF
Unit 5_Social Engineering and Cyberstalking.pdf
PDF
Unit 5_Classification of Cyber Crimes.pdf
PDF
Unit 5_Introduction to Cyber Security.pdf
PDF
Unit 4_SSL_Handshake Protocol_Record Layer Protocol.pdf
PDF
Unit 4_IPSec_AH_ESP_IKE_SA_Tunnel_Transport.pdf
PDF
Unit 3_Private Key Management_Protection.pdf
PDF
Unit 3_Kerberos Protocol_Working_Version.pdf
PDF
Unit 3_Digital Certificate_Intro_Types.pdf
PDF
Unit 3_Digital Signature Model Details.pdf
PDF
Unit 3_Hash function and MD5 working.pdf
PDF
Unit 3_Secure Hash Algorithm_SHA_Working.pdf
PDF
AES Solved Example on Encryption all rounds.pdf
PDF
Unit 2_AES_AES_Structure_Encryption_Example.pdf
Unit 1_Data Validation_Validation Techniques.pdf
Unit 1_Concet of Feature-Feature Selection Methods.pdf
Unit 1_Introduction to ML_Types_Applications.pdf
Unit 6_Cyber Laws Indian Act_Digital Signature.pdf
Unit 6_DoS and DDoS_SQL Injection_tools.pdf
Unit 6_keylogger_Spywares_virus_worms.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 5_Social Engineering and Cyberstalking.pdf
Unit 5_Classification of Cyber Crimes.pdf
Unit 5_Introduction to Cyber Security.pdf
Unit 4_SSL_Handshake Protocol_Record Layer Protocol.pdf
Unit 4_IPSec_AH_ESP_IKE_SA_Tunnel_Transport.pdf
Unit 3_Private Key Management_Protection.pdf
Unit 3_Kerberos Protocol_Working_Version.pdf
Unit 3_Digital Certificate_Intro_Types.pdf
Unit 3_Digital Signature Model Details.pdf
Unit 3_Hash function and MD5 working.pdf
Unit 3_Secure Hash Algorithm_SHA_Working.pdf
AES Solved Example on Encryption all rounds.pdf
Unit 2_AES_AES_Structure_Encryption_Example.pdf
Ad

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Complications of Minimal Access Surgery at WLH
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Cell Types and Its function , kingdom of life
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Anesthesia in Laparoscopic Surgery in India
O5-L3 Freight Transport Ops (International) V1.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
VCE English Exam - Section C Student Revision Booklet
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
GDM (1) (1).pptx small presentation for students
Complications of Minimal Access Surgery at WLH
102 student loan defaulters named and shamed – Is someone you know on the list?
O7-L3 Supply Chain Operations - ICLT Program
Cell Types and Its function , kingdom of life
Supply Chain Operations Speaking Notes -ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
Final Presentation General Medicine 03-08-2024.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Microbial diseases, their pathogenesis and prophylaxis

Unit 1_Stack and Queue using Linked Organization.pdf

  • 1. Data Structures Sanjivani Rural Education Society’s Sanjivani College of Engineering, Kopargaon-423603 (An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune) NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified Department of Information Technology (NBAAccredited) Ms. K. D. Patil Assistant Professor
  • 2. Linked Organization • Introduction, References and Basic Types, Linked list ADT, Implementing Singly linked list, Doubly linked lists, Implementing Doubly linked list, Implementation of stack using Linked organization, Applications: well formed-ness of parenthesis, Implementation of queue using linked organization, cloning Data Structures, Linked list efficiency Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
  • 3. Learning Outcomes • At the end of this unit, student will able to- Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology
  • 4. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • The major problem with the stack implemented using an array is, it works only for a fixed number of data values • That means the amount of data must be specified at the beginning of the implementation itself • Stack implemented using an array is not suitable, when we don't know the size of data which we are going to use • The stack implemented using linked list can work for an unlimited number of values • That means, stack implemented using linked list works for the variable size of data • So, there is no need to fix the size at the beginning of the implementation • The Stack implemented using linked list can organize as many data values as we want.
  • 5. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • In linked list implementation of a stack, every new element is inserted as 'top' element. • That means every newly inserted element is pointed by 'top'. • Whenever we want to remove an element from the stack, simply remove the node which is pointed by 'top' by moving 'top' to its previous node in the list. • The next field of the first element must be always NULL. • Here, the last inserted node is 99 and the first inserted node is 25. The order of elements inserted is 25, 32,50 and 99.
  • 6. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Push() Operation: Insertion at the beginning • Use the following steps to insert a new node into the stack. • Step 1 - Create a newNode with given value and allocate memory to it • Step 2 - Check whether stack is Empty (top == NULL) • Step 3 - If it is Empty, then set newNode → next = NULL. (This is the first node in the list, head) • Step 4 - If there are some nodes in the list already, then we have to add the new element in the beginning of the list (head position). For that, assign the address of the starting element, head to the address field of the new node and make the new node, top of the list (this is new head of the list now). • If it is Not Empty, then set newNode → next = top. • Step 5 - Finally, set top = newNode.
  • 7. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Push() Operation: Insertion at the beginning
  • 8. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Pop() Operation: Deletion at the beginning • Use the following steps to delete a node from the stack. • Step 1 - Check whether stack is Empty (top == NULL). • Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the function (An underflow condition will occur when we try to pop an element when the Stack is already empty. ) • Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'. (In stack, the elements are popped only from one end, therefore, the value stored in the head pointer must be deleted) • Step 4 - Then set 'top = top → next'. (The next node of the head node now becomes the head node.) • Step 5 - Finally, delete 'temp'. (free(temp)). (After deletion the node must be freed
  • 9. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Pop() Operation: Deletion at the beginning
  • 10. Stack using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Display() Operation: • Use the following steps to delete a node from the stack. • Step 1 - Check whether stack is Empty (top == NULL). • Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the function. • Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize with top. (Copy the head pointer into a temporary pointer) • Step 4 - Display 'temp → data' and move it to the next node. Repeat the same until temp reaches to the first node in the stack. (temp → next != NULL). • Step 5 - Finally! Display 'temp → data ---> NULL'.
  • 11. Time and Space Complexity of Stack Implementation using Linked List Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • The time complexity for various methods is written below: • push(): O(1) - as we are not traversing the whole list. • pop(): O(1) - as we are not traversing the entire list. • peek(): O(1) - as we are printing the head node • isEmpty(): O(1) - as we are checking only the head node. • display(): O(n) - As we are traversing through the whole list it will be O(n), where n is the number of nodes present in the linked list • Space Complexity for implementation of stack using linked list is O(n) for every operation.
  • 12. Advantages of Stack Implementation using Linked List Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Dynamic size: • The size of the stack can be adjusted dynamically as the linked list can grow or shrink according to the elements pushed or popped. • Efficient memory utilization: • The linked list uses only as much memory as required by the elements in the stack, whereas an array-based implementation might have to allocate extra memory to accommodate growth. • Flexibility: • Linked list implementation provides more flexibility than an array-based implementation as elements can be added or removed anywhere in the list.
  • 13. Advantages of Stack Implementation using Linked List Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Ease of implementation: • Implementing a stack using linked list is easier as it only requires a few basic operations to be performed on the linked list such as adding and removing elements from the beginning. • Improved performance: • The linked list implementation can provide improved performance compared to an array-based implementation, especially when dealing with large stacks, as inserting or removing elements from the beginning of the linked list is an O(1) operation.
  • 14. Disadvantages of Stack Implementation using Linked List Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Increased memory usage: • As each element in the stack is stored as a separate node, linked list implementation of stack takes up more memory than other implementations such as arrays. • Slower performance: • Operations on the linked list take more time compared to arrays, as accessing elements in linked lists require traversing through multiple nodes. • Complexity: • Linked list implementation of the stack requires more complex coding compared to other implementations such as arrays, leading to longer development time and more bugs. • Pointer management: • Managing pointers in linked lists is more challenging compared to arrays, leading to increased risk of bugs and data corruption.
  • 15. Well formedness of Parenthesis (stack application) Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Given an expression string expression, examine whether the pairs and the orders of “,“, “-”, “(“, “)”, “*“, “+” are correct in the given expression. • To test that, put all the opening brackets in the stack. • Whenever you hit a closing bracket, search if the top of the stack is the opening bracket of the same nature. • If this holds then pop the stack and continue the iteration. • In the end if the stack is empty, it means all brackets are balanced or well-formed. Otherwise, they are not balanced. Sample A Input string: "{}[](){}{([{()}])}" Output: expression is balanced Sample B Input string: "{}[](" Output: expression is not balanced
  • 16. Well formedness of Parenthesis (stack application) Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Follow the steps mentioned below to implement the idea: • Declare a character stack (say temp). • Now traverse the string exp. • If the current character is a starting bracket ( ‘(‘ or ‘,‘ or ‘*‘ ) then push it to stack. • If the current character is a closing bracket ( ‘)’ or ‘-’ or ‘+’ ) then pop from the stack and if the popped character is the matching starting bracket then fine. • Else brackets are Not Balanced. • After complete traversal, if some starting brackets are left in the stack then the expression is Not balanced, else Balanced.
  • 17. Well formedness of Parenthesis (stack application) Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology import java.util.*; public class BalancedBrackets { static boolean areBracketsBalanced(String expr) { Deque<Character> stack = new ArrayDeque<Character>(); // Traversing the Expression for (int i = 0; i < expr.length(); i++) { char x = expr.charAt(i); if (x == '(' || x == '[' || x == '{') { // Push the element in the stack stack.push(x); continue; }
  • 18. Well formedness of Parenthesis (stack application) Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology // If current character is not opening bracket, then it must be closing. So stack cannot be empty at this point. if (stack.isEmpty()) return false; char check; switch (x) { case ')': check = stack.pop(); if (check == '{' || check == '[') return false; break; case '}': check = stack.pop(); if (check == '(' || check == '[') return false; break;
  • 19. Well formedness of Parenthesis (stack application) Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology case ']': check = stack.pop(); if (check == '(' || check == '{') return false; break; } } return (stack.isEmpty()); // Check Empty Stack } public static void main(String[] args) { String expr = “,*()+-"; if (areBracketsBalanced(expr)) System.out.println("Balanced "); else System.out.println("Not Balanced "); } }
  • 20. Queue using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • In a linked queue, each node of the queue consists of two fields, i.e., data field and reference field. • Each entity of the linked queue points to its immediate next entity in the memory. • To keep track of the front and rear node, two pointers are preserved in the memory. • The first pointer stores the location where the queue starts. • Another pointer keeps track of the last data element of a queue.
  • 21. Queue using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • enQueue(value) Operation: Insertion at the end • We can use the following steps to insert a new node into the queue. • The insertion in a linked queue is performed at the rear end by updating the address value of the previous node where a rear pointer is pointing. • Step 1 - Create a newNode with given value and set 'newNode → next' to NULL. • Step 2 - Check whether queue is Empty (rear == NULL) • Step 3 - If it is Empty then, set front = newNode and rear = newNode. • Step 4 - If it is Not Empty then, set rear → next = newNode and rear = newNode.
  • 22. Queue using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • enQueue(value) Operation: Insertion at the end
  • 23. Queue using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • deQueue() Operation: deletion at the beginning • We can use the following steps to delete a node from the queue. • Step 1 - Check whether queue is Empty (front == NULL). • Step 2 - If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate from the function • Step 3 - If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'. • Step 4 - Then set 'front = front → next' and delete 'temp' (free(temp)).
  • 24. Queue using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • deQueue() Operation: deletion at the beginning
  • 25. Queue using Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • display() Operation: • We can use the following steps to display the queue. • Step 1 - Check whether queue is Empty (front == NULL). • Step 2 - If it is Empty then, display 'Queue is Empty!!!' and terminate the function. • Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with front. • Step 4 - Display 'temp → data' and move it to the next node. Repeat the same until 'temp' reaches to 'rear' (temp → next != NULL). • Step 5 - Display 'temp → data ---> NULL'.
  • 26. Time and Space Complexity of Queue Implementation using Linked List Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • The time complexity for various methods is written below: • enqueue(): O(1) – Best, O(n) – Average, Worst • dequeue(): O(1) – Best, O(n) – Average, Worst • isEmpty(): O(1) • display(): O(n) – Best, O(n) – Average, Worst
  • 27. Sequential Vs. Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology Sr. No. Linked Organization Sequential Organization 1. Data is stored in nodes that are linked together Data is stored in a linear sequence 2. Each node contains data and a pointer to the next node Each element is stored one after the other 3. Allows for fast insertions and deletions Allows for fast traversal and access 4. More complex to implement Simpler to implement 5. Can be used for implementing data structures like linked lists and trees Can be used for implementing data structures like arrays and stacks 6. Requires more memory for pointers Less memory is required as no pointers needed 7. Can be used for dynamic data structures Suitable for static data structures 8. Flexible in terms of size and structure Fixed-size and structure 9. Random access is not possible Random access is possible
  • 28. Sequential Vs. Linked Organization Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology Sr. No. Linked Organization Sequential Organization 10. Pointers may be pointing to null or non-existent memory in case of broken links All elements are stored in contiguous memory 11. Can have multiple pointers in case of bidirectional links Only one pointer is required to traverse the list 12. Can have a circular linked list Only a linear sequential list is possible 13. Can have multiple head and tail pointers Only one head and tail pointer is required 14. Can have variable length of data in each node Fixed length of data in each element 15. Can be used for implementing more complex data structures like graphs. Can be used for simple data structures like queues and stacks.
  • 29. Cloning Data Structure Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Abstraction allows for a data structure to be treated as a single object, even though the encapsulated implementation of the structure might rely on a more complex combination of many objects. • In a programming environment, a common expectation is that a copy of an object has its own state and that, once made, the copy is independent of the original (for example, so that changes to one do not directly affect the other). • Cloning of Data Structures is defined as creating a duplicate or copy of an existing data structure while maintaining its contents and structure.
  • 30. Cloning Data Structure Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Depending on the Data Structures type, the cloning process can vary. • Cloning allows you to work with the copy independently, making modifications without affecting the original data structure. • In java, the universal Object superclass defines a method named clone, which can be used to produce what is known as a shallow copy of an object. • This uses the standard assignment semantics to assign the value of each field of the new object equal to the corresponding field of the existing object that is being copied.
  • 31. Cloning Data Structure Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • The reason this is known as a shallow copy is because if the field is a reference type, then an initialization of the form duplicate.field = original.field causes the field of the new object to refer to the same underlying instance as the field of the original object. • A shallow copy is not always appropriate for all classes, and therefore, Java intentionally disables use of the clone( ) method by declaring it as protected, and by having it throw a CloneNotSupportedException when called. • The author of a class must explicitly declare support for cloning by formally declaring that the class implements the Cloneable interface, and by declaring a public version of the clone( ) method.
  • 32. Cloning Arrays Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Arrays support some special syntaxes such as a[k] and a.length • But they are objects, and that array variables are reference variables. • Example: consider the following code: • The assignment of variable backup to data does not create any new array, it simply creates a new alias for the same array.
  • 33. Cloning Arrays Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • If we want to make a copy of the array, data, and assign a reference to the new array to variable, backup, we should write: backup = data.clone( ); • The clone method, when executed on an array, initializes each cell of the new array to the value that is stored in the corresponding cell of the original array as follows.
  • 34. Cloning Lists Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Clone() method of a class in Java is used to create a new instance of a class of the current object and initialized all its fields with the contents of the specified object. • To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. • Syntax: protected Object clone() throws CloneNotSupportedException
  • 35. Cloning Lists Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • Steps: • Create a cloneable class, which has the clone method overridden. • Create a list of the class objects from an array using the asList method. • Create an empty list. • Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list.
  • 36. Cloning Lists Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Class needs to be cloneable class sample implements Cloneable { String username; String msg; sample (String username, String msg) // Constructor { this.username = username; this.msg = msg; } public String toString() // To print the objects in the desired format { return "n" + username + "n" + msg + "n"; } protected sample clone() // Overriding the inbuilt clone class { return new sample(username, msg); } } // Program to clone a List in Java class Example { public static void main(String[] args) { // Creating a list List<sample> original = Arrays.asList (new sample(“Hello", “Students")); // Creating an empty list List<sample> cloned_list = new ArrayList<sample>(); // Looping through the list and cloning each element for (sample temp : original) cloned_list.add(temp.clone()); System.out.println(cloned_list); } }
  • 37. Cloning stack Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • The clone() method of stack class is used to return a shallow copy of this Stack. • It just creates a copy of the Stack. • The copy will have a reference to a clone of the internal data array but not a reference to the original internal data array. • Syntax: stack.clone()
  • 38. Cloning stack Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology import java.util.*; public class StackDemo { public static void main(String args[]) { Stack<String> stack = new Stack<String>(); // Creating an empty Stack stack.add("Welcome"); // Use add() method to add elements into the Stack stack.add("To"); stack.add(“Data Structures Class"); System.out.println("Stack: " + stack); // Displaying the Stack Object copy_Stack = stack.clone(); // Creating another Stack to copy System.out.println("The cloned Stack is: " + copy_Stack); // Displaying the copy of Stack } }
  • 39. References Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology • R. Lafore, “Data structures and Algorithms in Java”, Pearson education, ISBN: 9788 131718124. • Michael Goodrich, Roberto Tamassia, Michael H. Goldwasser, “Data Structures and Algorithms in Java”, 6th edition, wiley publication, ISBN: 978-1-118-77133-4 • R. Gilberg, B. Forouzan, “Data Structure: A Pseudo code approach with C++”, Cengage Learning.
  • 40. Data Structures – Unit 1 Ms. K. D. Patil Department of Information Technology Thank You!!! Happy Learning!!!