尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
Stacks, Queues, and Deques
2
Stacks, Queues, and Deques
 A stack is a last in, first out (LIFO) data structure
 Items are removed from a stack in the reverse order from the
way they were inserted
 A queue is a first in, first out (FIFO) data structure
 Items are removed from a queue in the same order as they
were inserted
 A deque is a double-ended queue—items can be
inserted and removed at either end
3
Array implementation of stacks
 To implement a stack, items are inserted and removed at
the same end (called the top)
 Efficient array implementation requires that the top of
the stack be towards the center of the array, not fixed at
one end
 To use an array to implement a stack, you need both the
array itself and an integer
 The integer tells you either:

Which location is currently the top of the stack, or

How many elements are in the stack
4
Pushing and popping
 If the bottom of the stack is at location 0, then an empty
stack is represented by top = -1 or count = 0
 To add (push) an element, either:
 Increment top and store the element in stk[top], or
 Store the element in stk[count] and increment count
 To remove (pop) an element, either:
 Get the element from stk[top] and decrement top, or
 Decrement count and get the element in stk[count]
top = 3 or count = 4
0 1 2 3 4 5 6 7 8 9
17 23 97 44stk:
5
After popping
 When you pop an element, do you just leave the “deleted”
element sitting in the array?
 The surprising answer is, “it depends”
 If this is an array of primitives, or if you are programming in C or C++,
then doing anything more is just a waste of time
 If you are programming in Java, and the array contains objects, you should
set the “deleted” array element to null
 Why? To allow it to be garbage collected!
top = 2 or count = 3
0 1 2 3 4 5 6 7 8 9
17 23 97 44stk:
6
Sharing space
 Of course, the bottom of the stack could be at the other end
top = 6 or count = 4
17239744
0 1 2 3 4 5 6 7 8 9
stk:
 Sometimes this is done to allow two stacks to share the same
storage area
topStk2 = 6
1723974449 57 3
0 1 2 3 4 5 6 7 8 9
stks:
topStk1 = 2
7
Error checking
 There are two stack errors that can occur:
 Underflow: trying to pop (or peek at) an empty stack
 Overflow: trying to push onto an already full stack
 For underflow, you should throw an exception
 If you don’t catch it yourself, Java will throw an
ArrayIndexOutOfBounds exception
 You could create your own, more informative exception
 For overflow, you could do the same things
 Or, you could check for the problem, and copy
everything into a new, larger array
8
Pointers and references
 In C and C++ we have “pointers,” while in Java
we have “references”
 These are essentially the same thing

The difference is that C and C++ allow you to modify pointers
in arbitrary ways, and to point to anything
 In Java, a reference is more of a “black box,” or ADT

Available operations are:
 dereference (“follow”)
 copy
 compare for equality

There are constraints on what kind of thing is referenced: for
example, a reference to an array of int can only refer to an
array of int
9
Creating references
 The keyword new creates a new object, but also returns
a reference to that object
 For example, Person p = new Person("John")
 new Person("John") creates the object and returns a
reference to it
 We can assign this reference to p, or use it in other ways
10
Creating links in Java
class Cell { int value; Cell next;
Cell (int v, Cell n) { value = v; next = n; }
}
Cell temp = new Cell(17, null);
temp = new Cell(23, temp);
temp = new Cell(97, temp);
Cell myStack = new Cell(44, temp);
44 97 23 17
myStack:
11
Linked-list implementation of stacks
 Since all the action happens at the top of a stack, a singly-
linked list (SLL) is a fine way to implement it
 The header of the list points to the top of the stack
44 97 23 17
myStack:
 Pushing is inserting an element at the front of the list
 Popping is removing an element from the front of the list
12
Linked-list implementation details
 With a linked-list representation, overflow will not
happen (unless you exhaust memory, which is
another kind of problem)
 Underflow can happen, and should be handled the
same way as for an array implementation
 When a node is popped from a list, and the node
references an object, the reference (the pointer in
the node) does not need to be set to null
 Unlike an array implementation, it really is removed--
you can no longer get to it from the linked list
 Hence, garbage collection can occur as appropriate
13
Array implementation of queues
 A queue is a first in, first out (FIFO) data structure
 This is accomplished by inserting at one end (the rear) and
deleting from the other (the front)
 To insert: put new element in location 4, and set rear to 4
 To delete: take element from location 0, and set front to 1
17 23 97 44
0 1 2 3 4 5 6 7
myQueue:
rear = 3front = 0
14
Array implementation of queues
 Notice how the array contents “crawl” to the right as elements are
inserted and deleted
 This will be a problem after a while!
17 23 97 44 333After insertion:
23 97 44 333After deletion:
rear = 4front = 1
17 23 97 44Initial queue:
rear = 3front = 0
15
Circular arrays
 We can treat the array holding the queue elements as
circular (joined at the ends)
44 55 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 1 front = 5
 Elements were added to this queue in the order 11, 22,
33, 44, 55, and will be removed in the same order
 Use: front = (front + 1) % myQueue.length;
and: rear = (rear + 1) % myQueue.length;
16
Full and empty queues
 If the queue were to become completely full, it would look
like this:
 If we were then to remove all eight elements, making the queue
completely empty, it would look like this:
44 55 66 77 88 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 4 front = 5
0 1 2 3 4 5 6 7
myQueue:
rear = 4 front = 5
This is a problem!
17
Full and empty queues: solutions
 Solution #1: Keep an additional variable
 Solution #2: (Slightly more efficient) Keep a gap between
elements: consider the queue full when it has n-1 elements
44 55 66 77 88 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 4 front = 5count = 8
44 55 66 77 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 3 front = 5
18
Linked-list implementation of queues
 In a queue, insertions occur at one end, deletions at
the other end
 Operations at the front of a singly-linked list (SLL)
are O(1), but at the other end they are O(n)
 Because you have to find the last element each time
 BUT: there is a simple way to use a singly-linked
list to implement both insertions and deletions in
O(1) time
 You always need a pointer to the first thing in the list
 You can keep an additional pointer to the last thing in the
list
19
SLL implementation of queues
 In an SLL you can easily find the successor of a
node, but not its predecessor
 Remember, pointers (references) are one-way
 If you know where the last node in a list is, it’s
hard to remove that node, but it’s easy to add a
node after it
 Hence,
 Use the first element in an SLL as the front of the queue
 Use the last element in an SLL as the rear of the queue
 Keep pointers to both the front and the rear of the SLL
20
Enqueueing a node
17
Node to be
enqueued
To enqueue (add) a node:
Find the current last node
Change it to point to the new last node
Change the last pointer in the list header
2344
last
first
97
21
Dequeueing a node
 To dequeue (remove) a node:
 Copy the pointer from the first node into the header
44 97 23 17
last
first
22
Queue implementation details
 With an array implementation:
 you can have both overflow and underflow
 you should set deleted elements to null
 With a linked-list implementation:
 you can have underflow
 overflow is a global out-of-memory condition
 there is no reason to set deleted elements to null
23
Deques
 A deque is a double-ended queue
 Insertions and deletions can occur at either end
 Implementation is similar to that for queues
 Deques are not heavily used
 You should know what a deque is, but we won’t
explore them much further
24
Stack ADT
 The Stack ADT, as provided in java.util.Stack:
 Stack(): the constructor
 boolean empty() (but also inherits isEmpty())
 Object push(Object item)
 Object peek()
 Object pop()
 int search(Object o): Returns the 1-based position of the
object on this stack
25
A queue ADT
 Java provides a queue interface
 Here are the usual operations on a queue:
 Queue(): the constructor
 boolean isEmpty()
 Object enqueue(Object item): add at element at the rear
 Object dequeue(): remove an element from the front
 Object peek(): look at the front element
 int search(Object o): Returns the 1-based position from the
front of the queue
 Java’s interface uses goofy names:
 enqueue(Object)  offer(Object)
 dequeue()  poll()
26
A deque ADT
 Java does not provide a deque class
 Here is a possible deque ADT:
 Deque(): the constructor
 boolean isEmpty()
 Object addAtFront(Object item)
 Object addAtRear(Object item)
 Object getFromFront()
 Object getFromRear()
 Object peekAtFront()
 Object peekAtRear()
 int search(Object o): Returns the 1-based position from the
front of the deque
27
Using ArrayLists
 You could implement a deque with
java.util.ArrayList:
 addAtFront(Object)  add(0, Object)
 addAtRear(Object item)  add(Object)
 getFromFront()  remove(0)
 getFromRear()  remove(size() – 1)
 If you did this, should you extend ArrayList or use it as
a field in your Deque class?
 Would this be a good implementation?
 Why or why not?
28
The End
Eclipse Hints
● Go to Window  Preferences... 
Java  Editor  Content Assist 
Typing and check everything
Try this for a couple of days before you
decide you hate it!

More Related Content

What's hot

Queues
QueuesQueues
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
Stack
StackStack
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
somendra kumar
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
Rameesha Sadaqat
 
Linked list
Linked listLinked list
Linked list
akshat360
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
Jsaddam Hussain
 
stack presentation
stack presentationstack presentation
Singly link list
Singly link listSingly link list
Singly link list
Rojin Khadka
 
Graphs In Data Structure
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
Anuj Modi
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
NUPOORAWSARMOL
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
Amit Kumar Rathi
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
Rojan Pariyar
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 

What's hot (20)

Queues
QueuesQueues
Queues
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Stack
StackStack
Stack
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
 
Linked list
Linked listLinked list
Linked list
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
stack presentation
stack presentationstack presentation
stack presentation
 
Singly link list
Singly link listSingly link list
Singly link list
 
Graphs In Data Structure
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
Linked list
Linked listLinked list
Linked list
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 

Viewers also liked

Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
Amit Vats
 
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Ariel Carrion
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
Ramzi Alqrainy
 
Linked List Implementation of Deque in C
Linked List Implementation of Deque in CLinked List Implementation of Deque in C
Linked List Implementation of Deque in C
Kasun Ranga Wijeweera
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
SANTOSH RATH
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
Ain-ul-Moiz Khawaja
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
Luis Goldster
 
Data structure-questions
Data structure-questionsData structure-questions
Data structure-questions
Shekhar Chander
 
Data structures question paper anna university
Data structures question paper anna universityData structures question paper anna university
Data structures question paper anna university
sangeethajames07
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
Reggie Niccolo Santos
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues ii
Tech_MX
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
Tushar Aneyrao
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
PTCL
 

Viewers also liked (15)

Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
Formulacion de-qumica-inorganica-120319205240-phpapp01-131119105305-phpapp02-...
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
 
Linked List Implementation of Deque in C
Linked List Implementation of Deque in CLinked List Implementation of Deque in C
Linked List Implementation of Deque in C
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Data structure-questions
Data structure-questionsData structure-questions
Data structure-questions
 
Data structures question paper anna university
Data structures question paper anna universityData structures question paper anna university
Data structures question paper anna university
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues ii
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 

Similar to Stacks, Queues, Deques

23 stacks-queues-deques
23 stacks-queues-deques23 stacks-queues-deques
23 stacks-queues-deques
Rishabh Jindal
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
Rai University
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
Victor Palmar
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
SherinRappai
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
Pulkitmodi1998
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
Ssankett Negi
 
Review of basic data structures
Review of basic data structuresReview of basic data structures
Review of basic data structures
Deepa Rani
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
skilljiolms
 
LEC3-DS ALGO(updated).pdf
LEC3-DS  ALGO(updated).pdfLEC3-DS  ALGO(updated).pdf
LEC3-DS ALGO(updated).pdf
MuhammadUmerIhtisham
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
Teksify
 
Queue data structures and operation on data structures
Queue data structures and operation on data structuresQueue data structures and operation on data structures
Queue data structures and operation on data structures
muskans14
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
iqbalphy1
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
arpitaeron555
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
MuhammadUmerIhtisham
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
vtunali
 
stack coding.pptx
stack coding.pptxstack coding.pptx
stack coding.pptx
JamJahanzaib
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
maneesh boddu
 

Similar to Stacks, Queues, Deques (20)

23 stacks-queues-deques
23 stacks-queues-deques23 stacks-queues-deques
23 stacks-queues-deques
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Review of basic data structures
Review of basic data structuresReview of basic data structures
Review of basic data structures
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
LEC3-DS ALGO(updated).pdf
LEC3-DS  ALGO(updated).pdfLEC3-DS  ALGO(updated).pdf
LEC3-DS ALGO(updated).pdf
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
 
Queue data structures and operation on data structures
Queue data structures and operation on data structuresQueue data structures and operation on data structures
Queue data structures and operation on data structures
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdfCEN 235 4. Abstract Data Types - Queue and Stack.pdf
CEN 235 4. Abstract Data Types - Queue and Stack.pdf
 
stack coding.pptx
stack coding.pptxstack coding.pptx
stack coding.pptx
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 

More from A-Tech and Software Development

Online Bus Reservation System
Online Bus Reservation SystemOnline Bus Reservation System
Online Bus Reservation System
A-Tech and Software Development
 
Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02
A-Tech and Software Development
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
A-Tech and Software Development
 
Survey Of Software Houses
Survey Of Software HousesSurvey Of Software Houses
Survey Of Software Houses
A-Tech and Software Development
 
Traffic signal's
Traffic signal'sTraffic signal's
Canteen Store Department
Canteen Store DepartmentCanteen Store Department
Canteen Store Department
A-Tech and Software Development
 
Chick development
Chick developmentChick development
Peripheral devices
Peripheral devicesPeripheral devices
Bank System
Bank SystemBank System
Bank System
Bank SystemBank System
Bank Management System
Bank Management SystemBank Management System
Bank Management System
A-Tech and Software Development
 
Village Life Of Pakistan
Village Life Of PakistanVillage Life Of Pakistan
Village Life Of Pakistan
A-Tech and Software Development
 
Role of media in our society
Role of media in our societyRole of media in our society
Role of media in our society
A-Tech and Software Development
 

More from A-Tech and Software Development (13)

Online Bus Reservation System
Online Bus Reservation SystemOnline Bus Reservation System
Online Bus Reservation System
 
Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
 
Survey Of Software Houses
Survey Of Software HousesSurvey Of Software Houses
Survey Of Software Houses
 
Traffic signal's
Traffic signal'sTraffic signal's
Traffic signal's
 
Canteen Store Department
Canteen Store DepartmentCanteen Store Department
Canteen Store Department
 
Chick development
Chick developmentChick development
Chick development
 
Peripheral devices
Peripheral devicesPeripheral devices
Peripheral devices
 
Bank System
Bank SystemBank System
Bank System
 
Bank System
Bank SystemBank System
Bank System
 
Bank Management System
Bank Management SystemBank Management System
Bank Management System
 
Village Life Of Pakistan
Village Life Of PakistanVillage Life Of Pakistan
Village Life Of Pakistan
 
Role of media in our society
Role of media in our societyRole of media in our society
Role of media in our society
 

Recently uploaded

How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17
Celine George
 
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
Kalna College
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
 
Keynote given on June 24 for MASSP at Grand Traverse City
Keynote given on June 24 for MASSP at Grand Traverse CityKeynote given on June 24 for MASSP at Grand Traverse City
Keynote given on June 24 for MASSP at Grand Traverse City
PJ Caposey
 
Interprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdfInterprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdf
Ben Aldrich
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
Sarojini38
 
Slides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptxSlides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptx
shabeluno
 
(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
MJDuyan
 
pol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdfpol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdf
BiplabHalder13
 
How to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRMHow to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRM
Celine George
 
The basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxThe basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptx
heathfieldcps1
 
Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17
Celine George
 
IoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdfIoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdf
roshanranjit222
 
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptxScience-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Catherine Dela Cruz
 
BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...
BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...
BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...
Nguyen Thanh Tu Collection
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
Infosec
 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
ShwetaGawande8
 
The Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptxThe Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptx
PriyaKumari928991
 
Talking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual AidsTalking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual Aids
MattVassar1
 

Recently uploaded (20)

How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17
 
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
 
Keynote given on June 24 for MASSP at Grand Traverse City
Keynote given on June 24 for MASSP at Grand Traverse CityKeynote given on June 24 for MASSP at Grand Traverse City
Keynote given on June 24 for MASSP at Grand Traverse City
 
Interprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdfInterprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdf
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
 
Slides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptxSlides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptx
 
(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
 
pol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdfpol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdf
 
How to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRMHow to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRM
 
The basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxThe basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptx
 
Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17
 
IoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdfIoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdf
 
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptxScience-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
 
BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...
BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...
BỘ BÀI TẬP TEST THEO UNIT - FORM 2025 - TIẾNG ANH 12 GLOBAL SUCCESS - KÌ 1 (B...
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
 
The Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptxThe Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptx
 
Talking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual AidsTalking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual Aids
 

Stacks, Queues, Deques

  • 2. 2 Stacks, Queues, and Deques  A stack is a last in, first out (LIFO) data structure  Items are removed from a stack in the reverse order from the way they were inserted  A queue is a first in, first out (FIFO) data structure  Items are removed from a queue in the same order as they were inserted  A deque is a double-ended queue—items can be inserted and removed at either end
  • 3. 3 Array implementation of stacks  To implement a stack, items are inserted and removed at the same end (called the top)  Efficient array implementation requires that the top of the stack be towards the center of the array, not fixed at one end  To use an array to implement a stack, you need both the array itself and an integer  The integer tells you either:  Which location is currently the top of the stack, or  How many elements are in the stack
  • 4. 4 Pushing and popping  If the bottom of the stack is at location 0, then an empty stack is represented by top = -1 or count = 0  To add (push) an element, either:  Increment top and store the element in stk[top], or  Store the element in stk[count] and increment count  To remove (pop) an element, either:  Get the element from stk[top] and decrement top, or  Decrement count and get the element in stk[count] top = 3 or count = 4 0 1 2 3 4 5 6 7 8 9 17 23 97 44stk:
  • 5. 5 After popping  When you pop an element, do you just leave the “deleted” element sitting in the array?  The surprising answer is, “it depends”  If this is an array of primitives, or if you are programming in C or C++, then doing anything more is just a waste of time  If you are programming in Java, and the array contains objects, you should set the “deleted” array element to null  Why? To allow it to be garbage collected! top = 2 or count = 3 0 1 2 3 4 5 6 7 8 9 17 23 97 44stk:
  • 6. 6 Sharing space  Of course, the bottom of the stack could be at the other end top = 6 or count = 4 17239744 0 1 2 3 4 5 6 7 8 9 stk:  Sometimes this is done to allow two stacks to share the same storage area topStk2 = 6 1723974449 57 3 0 1 2 3 4 5 6 7 8 9 stks: topStk1 = 2
  • 7. 7 Error checking  There are two stack errors that can occur:  Underflow: trying to pop (or peek at) an empty stack  Overflow: trying to push onto an already full stack  For underflow, you should throw an exception  If you don’t catch it yourself, Java will throw an ArrayIndexOutOfBounds exception  You could create your own, more informative exception  For overflow, you could do the same things  Or, you could check for the problem, and copy everything into a new, larger array
  • 8. 8 Pointers and references  In C and C++ we have “pointers,” while in Java we have “references”  These are essentially the same thing  The difference is that C and C++ allow you to modify pointers in arbitrary ways, and to point to anything  In Java, a reference is more of a “black box,” or ADT  Available operations are:  dereference (“follow”)  copy  compare for equality  There are constraints on what kind of thing is referenced: for example, a reference to an array of int can only refer to an array of int
  • 9. 9 Creating references  The keyword new creates a new object, but also returns a reference to that object  For example, Person p = new Person("John")  new Person("John") creates the object and returns a reference to it  We can assign this reference to p, or use it in other ways
  • 10. 10 Creating links in Java class Cell { int value; Cell next; Cell (int v, Cell n) { value = v; next = n; } } Cell temp = new Cell(17, null); temp = new Cell(23, temp); temp = new Cell(97, temp); Cell myStack = new Cell(44, temp); 44 97 23 17 myStack:
  • 11. 11 Linked-list implementation of stacks  Since all the action happens at the top of a stack, a singly- linked list (SLL) is a fine way to implement it  The header of the list points to the top of the stack 44 97 23 17 myStack:  Pushing is inserting an element at the front of the list  Popping is removing an element from the front of the list
  • 12. 12 Linked-list implementation details  With a linked-list representation, overflow will not happen (unless you exhaust memory, which is another kind of problem)  Underflow can happen, and should be handled the same way as for an array implementation  When a node is popped from a list, and the node references an object, the reference (the pointer in the node) does not need to be set to null  Unlike an array implementation, it really is removed-- you can no longer get to it from the linked list  Hence, garbage collection can occur as appropriate
  • 13. 13 Array implementation of queues  A queue is a first in, first out (FIFO) data structure  This is accomplished by inserting at one end (the rear) and deleting from the other (the front)  To insert: put new element in location 4, and set rear to 4  To delete: take element from location 0, and set front to 1 17 23 97 44 0 1 2 3 4 5 6 7 myQueue: rear = 3front = 0
  • 14. 14 Array implementation of queues  Notice how the array contents “crawl” to the right as elements are inserted and deleted  This will be a problem after a while! 17 23 97 44 333After insertion: 23 97 44 333After deletion: rear = 4front = 1 17 23 97 44Initial queue: rear = 3front = 0
  • 15. 15 Circular arrays  We can treat the array holding the queue elements as circular (joined at the ends) 44 55 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 1 front = 5  Elements were added to this queue in the order 11, 22, 33, 44, 55, and will be removed in the same order  Use: front = (front + 1) % myQueue.length; and: rear = (rear + 1) % myQueue.length;
  • 16. 16 Full and empty queues  If the queue were to become completely full, it would look like this:  If we were then to remove all eight elements, making the queue completely empty, it would look like this: 44 55 66 77 88 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 4 front = 5 0 1 2 3 4 5 6 7 myQueue: rear = 4 front = 5 This is a problem!
  • 17. 17 Full and empty queues: solutions  Solution #1: Keep an additional variable  Solution #2: (Slightly more efficient) Keep a gap between elements: consider the queue full when it has n-1 elements 44 55 66 77 88 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 4 front = 5count = 8 44 55 66 77 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 3 front = 5
  • 18. 18 Linked-list implementation of queues  In a queue, insertions occur at one end, deletions at the other end  Operations at the front of a singly-linked list (SLL) are O(1), but at the other end they are O(n)  Because you have to find the last element each time  BUT: there is a simple way to use a singly-linked list to implement both insertions and deletions in O(1) time  You always need a pointer to the first thing in the list  You can keep an additional pointer to the last thing in the list
  • 19. 19 SLL implementation of queues  In an SLL you can easily find the successor of a node, but not its predecessor  Remember, pointers (references) are one-way  If you know where the last node in a list is, it’s hard to remove that node, but it’s easy to add a node after it  Hence,  Use the first element in an SLL as the front of the queue  Use the last element in an SLL as the rear of the queue  Keep pointers to both the front and the rear of the SLL
  • 20. 20 Enqueueing a node 17 Node to be enqueued To enqueue (add) a node: Find the current last node Change it to point to the new last node Change the last pointer in the list header 2344 last first 97
  • 21. 21 Dequeueing a node  To dequeue (remove) a node:  Copy the pointer from the first node into the header 44 97 23 17 last first
  • 22. 22 Queue implementation details  With an array implementation:  you can have both overflow and underflow  you should set deleted elements to null  With a linked-list implementation:  you can have underflow  overflow is a global out-of-memory condition  there is no reason to set deleted elements to null
  • 23. 23 Deques  A deque is a double-ended queue  Insertions and deletions can occur at either end  Implementation is similar to that for queues  Deques are not heavily used  You should know what a deque is, but we won’t explore them much further
  • 24. 24 Stack ADT  The Stack ADT, as provided in java.util.Stack:  Stack(): the constructor  boolean empty() (but also inherits isEmpty())  Object push(Object item)  Object peek()  Object pop()  int search(Object o): Returns the 1-based position of the object on this stack
  • 25. 25 A queue ADT  Java provides a queue interface  Here are the usual operations on a queue:  Queue(): the constructor  boolean isEmpty()  Object enqueue(Object item): add at element at the rear  Object dequeue(): remove an element from the front  Object peek(): look at the front element  int search(Object o): Returns the 1-based position from the front of the queue  Java’s interface uses goofy names:  enqueue(Object)  offer(Object)  dequeue()  poll()
  • 26. 26 A deque ADT  Java does not provide a deque class  Here is a possible deque ADT:  Deque(): the constructor  boolean isEmpty()  Object addAtFront(Object item)  Object addAtRear(Object item)  Object getFromFront()  Object getFromRear()  Object peekAtFront()  Object peekAtRear()  int search(Object o): Returns the 1-based position from the front of the deque
  • 27. 27 Using ArrayLists  You could implement a deque with java.util.ArrayList:  addAtFront(Object)  add(0, Object)  addAtRear(Object item)  add(Object)  getFromFront()  remove(0)  getFromRear()  remove(size() – 1)  If you did this, should you extend ArrayList or use it as a field in your Deque class?  Would this be a good implementation?  Why or why not?
  • 28. 28 The End Eclipse Hints ● Go to Window  Preferences...  Java  Editor  Content Assist  Typing and check everything Try this for a couple of days before you decide you hate it!
  翻译: