SlideShare a Scribd company logo
1 of 47
Download to read offline
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Stacks:
Implementation in
JAVA
Stacks: Implementation in JAVA page 2
© Dr. Jonathan (Yahya) Cazalas
Stacks – An Overview
 Stacks:
 Stacks are an Abstract Data Type
 Meaning, they are a data type that we must build
 (well, in JAVA, we do have a stack class…more on that later)
 We must define them and their behaviors
 So what is a stack?
 A data structure that stores information in the form of a
stack.
 Consists of a variable number of homogeneous elements
 i.e. elements of the same type
Stacks: Implementation in JAVA page 3
© Dr. Jonathan (Yahya) Cazalas
Stacks – An Overview
 Stacks:
 Access Policy:
 The access policy for a stack is simple: the first element
to be removed from the stack is the last element that was
placed onto the stack
 The main idea is that the last item placed on to the stack is the
first item removed from the stack
 Known as the “Last in, First out” access policy
 LIFO for short
 The classical example of a stack is cafeteria trays.
 New, clean trays are added to the top of the stack.
 and trays are also taken from the top
 So the last tray in is the first tray taken out
Stacks: Implementation in JAVA page 4
© Dr. Jonathan (Yahya) Cazalas
Stacks – An Overview
 Stacks:
 Basic Operations:
 PUSH:
 This PUSHes an item on top of the stack
 POP:
 This POPs off the top item in the stack and returns it
 Other important tidbit:
 The end of the stack,
 where PUSHes and POPs occur,
 is usually referred to as the TOP of the stack
Stacks: Implementation in JAVA page 5
© Dr. Jonathan (Yahya) Cazalas
Stacks – An Overview
 Stacks:
 Other useful operations:
 isEmpty:
 Typically implemented as a boolean function
 Returns TRUE if no items are in the stack
 isFull:
 Returns TRUE if no more items can be added to the stack
 In theory, a stack should NEVER become full
 Actual implementations do have limits on the number of
elements a stack can store
 top (also called “peek”):
 Simply returns the value at the top of the stack without actually
popping the stack.
Stacks: Implementation in JAVA page 6
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Implementation of Stacks in JAVA:
 As discussed on the previous lecture, there are
two obvious ways to implement stacks:
1) Using arrays
2) Using linked lists
 We will go over both…
Stacks: Implementation in JAVA page 7
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Implementation of Stacks in JAVA:
 Array:
 We will implement the stack as an array!
 What does this mean?
 This means that when you examine the code for the stack, in
fact, it is simply using an array!
 So then how is the array a stack? What makes it a stack?
 The BEHAVIOR!
 We said that an Abstract Data Type is defined based on
its behaviors (the operations it can perform).
 So we will restrict the behavior of the array.
 We will make the array behave like (act like) a stack!
Stacks: Implementation in JAVA page 8
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Implementation of Stacks in JAVA:
 Array:
 So we will restrict the behavior of the array.
 We will make the array behave like (act like) a stack!
 Example:
 With an array, you can insert anywhere or delete anywhere
 Insert at the beginning, middle, or end…anywhere!
 However:
 Since we are making this array behave like (act like) a stack:
 We will ONLY allow insertion at the “top”
 PUSH
 We will ONLY allow deletion at the “top”
 POP
 So now, our array has basically transformed into a stack!
Stacks: Implementation in JAVA page 9
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 What components will we need to store?
1) The array storing the elements
 The actual stack of values
 What else?
2) An index to the top of the stack
 We assume the bottom of the stack is index 0
 Meaning, the 1st element will be stored in index 0
 and we move up from there
3) The max size of the stack (maxSize)
 Of course, we could just use the array.length feature of
JAVA to give us the size of the array (which is maxSize)
Stacks: Implementation in JAVA page 10
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 Here is our class, StackArray:
 maxSize clearly represents the max number of items in
the stack
 If the stack becomes full, at that point, the top item will
be stored at index ‘maxSize-1’
public class StackArray {
private int[] stack;
private int top;
private int maxSize;
// Constructor and Methods here
}
Stacks: Implementation in JAVA page 11
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 Here is the constructor:
 So we set maxSize from the parameter size
 We then make the new array, stack
 Finally, we set top equal to -1
 Why?
class StackArray {
...
public StackArray(int size) {
maxSize = size;
stack = new int[maxSize];
top = -1;
}
Stacks: Implementation in JAVA page 12
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 Here is the constructor:
 When the stack has one element, what is saved in top?
 top is the index to the “top element”
 So if there is only one element, that element is at index zero!
 So top will have the value, 0, referring to the first cell
class StackArray {
...
public StackArray(int size) {
maxSize = size;
stack = new int[maxSize];
top = -1;
}
Stacks: Implementation in JAVA page 13
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 Here is the constructor:
 So when top is zero, that means we have ONE element
 How do we show that the stack is empty???
 We set top equal to -1
 This means that nothing is in the stack.
class StackArray {
...
public StackArray(int size) {
maxSize = size;
stack = new int[maxSize];
top = -1;
}
Stacks: Implementation in JAVA page 14
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 Here are the methods we will need to control our
stack behavior:
 public boolean isEmpty()
 public boolean isFull()
 public void push(int j)
 public int pop()
 public int top()
Stacks: Implementation in JAVA page 15
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 isEmpty:
 The isEmpty function simply checks if the stack has no
elements
 Based on what you know thus far, how would you
determine if the stack is empty?
 If the top currently equals -1!
 Here’s the code:
public boolean isEmpty() {
return (top == -1);
}
Stacks: Implementation in JAVA page 16
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 isFull:
 The isFull function checks to see if the stack is full
 How would we do this?
 Remember, maxSize is the max # of items in the stack
 Item 1 goes at index 0
 If the stack is full, the top item will be at index ‘maxSize-1’
 Here’s the code:
public boolean isFull() {
return (top == maxSize-1)
}
Stacks: Implementation in JAVA page 17
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 push:
 Remember, we can only push if the stack is not full
 Meaning, if there is room to push
 So if the stack is full
 We print an error message.
 Or throw an Exception, showing the push could not be done
 If there is room
 We increment top to point to the next space in the stack
 Then we simply copy the value into this new top position
Stacks: Implementation in JAVA page 18
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 push:
 To push an element, increment top to point to the next
space in the stack
 Then we simply copy the value into this new top position
 Here’s the code:
public void push(int value) {
if (isFull())
System.out.println(“Cannot PUSH; stack is full.”);
else
stack[++top] = value;
}
Stacks: Implementation in JAVA page 19
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 pop:
 Remember, we can only pop if the stack is not empty
 Meaning, there is at least one element to pop
 So if the stack is empty
 We print an error message
 Or throw an exception showing that we cannot pop
 If the stack has at least one element:
 We return the value at position top
 At the same time, we decrement top
 This makes the top “pointer” refer to the next item down in
the stack
Stacks: Implementation in JAVA page 20
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 pop:
 To pop an element, we simply return the top item in the
stack and then decrement top
 Here’s the code:
public int pop() {
if (isEmpty())
System.out.println(“Cannot POP; stack is empty.”);
else
return stack[top--];
}
Stacks: Implementation in JAVA page 21
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 top (or peek):
 The top method is very similar to pop
 Remember, we can only check for the top of the stack if
the stack is not empty
 Meaning, there is at least one element in the stack
 So if the stack is empty
 We print an error message
 If the stack has at least one element:
 We simply return the topmost element
 But we do NOT decrement
Stacks: Implementation in JAVA page 22
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 top:
 Simply returns the top item in the stack
 Here’s the code:
public int top() {
if (isEmpty())
System.out.println(“Cannot TOP; stack is empty.”);
else
return stack[top];
}
Stacks: Implementation in JAVA page 23
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Array Implementation of Stacks:
 The code shown here is only small pieces of the
code.
 Code is on Blackboard:
 You can also view a FULLY-FUNCITONAL Array
Implementation of a Stack on Blackboard.
Stacks: Implementation in JAVA page 24
© Dr. Jonathan (Yahya) Cazalas
Brief Interlude: HUGE Fail
Stacks: Implementation in JAVA page 25
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA page 26
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA page 27
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA page 28
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Implementation of Stacks in JAVA:
 Linked-list:
 We can also implement the stack as a linked-list!
 Advantage of no fixed size and dynamic memory
 What does this mean?
 This means that when you examine the code for the stack, in
fact, it is simply using a modified version of the linked-list code!
 So then how is the linked-list a stack?
 The BEHAVIOR!
 We will restrict the behavior of the linked-list.
 We will make the linked-list behave like (act like) a stack!
Stacks: Implementation in JAVA page 29
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Implementation of Stacks in JAVA:
 Linked-list:
 We will restrict the behavior of the linked-list.
 We will make the linked-list behave like (act like) a stack!
 Example:
 With a linked-list, you can insert anywhere or delete anywhere
 Insert at the beginning, middle, or end…anywhere!
 However:
 Since we are making this linked-list behave like a stack:
 We will ONLY allow insertion at the “top”
 PUSH
 We will ONLY allow deletion at the “top”
 POP
 So now, our linked-list has basically transformed into a stack!
Stacks: Implementation in JAVA page 30
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 We essentially use a standard linked list
 But we limit the functionality of a linked list
 Thus creating the behavior required of a stack
 Step 1:
 Choose the location of top!
 Where should we choose top to be? What is best?
 Top could be the “front” of the list OR the “end” of the list
 Which is better?
 If we choose top to be the end, we must traverse to the
end for every PUSH and every POP…a lot of traversing!
 BEST choice: we let top be the front of our list.
Stacks: Implementation in JAVA page 31
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 So top will refer to the front of our list.
 Therefore:
 A push is simply inserting into the front of the linked
list!
 This is the easiest type of insertion
 It only requires changing two references!
 A pop would be deleting the front node
 Again, the easiest type of deletion
 Only requiring changing two references!
 So, in fact, a linked-list version of a stack is EASIER to
code than a regular stack!
Stacks: Implementation in JAVA page 32
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 So each node will be an element of the stack
 Each node has a data value
 Each node also has a next
 We simply push (insert at front)
 And pop (delete the front node)
Stacks: Implementation in JAVA page 33
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 So we will create two classes (like Linked-Lists)
 StackNode.java (this is like the LLnode class)
 StackLL.java (this is like the LinkedList class)
 We use most of the SAME methods as used for
the Linked List class
 However, we RESTRICT the functionality
 Now, we cannot insert anywhere in the list
 We can only insert at the top (head)
 Now, we cannot delete from anywhere in the list
 We can only delete from the top (head)
Stacks: Implementation in JAVA page 34
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackNode.java
public class StackNode {
private int data;
private StackNode next;
// CONSTRUCTORS
public StackNode() {
data = 0;
next = null;
}
public StackNode(int data) {
this.data = data;
next = null;
}
public StackNode(int data, StackNode next) {
this.data = data;
this.next = next;
}
Stacks: Implementation in JAVA page 35
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
...
// ACCESSORS
public int getData() {
return data;
}
public StackNode getNext() {
return next;
}
// MUTATORS
public void setData(int data) {
this.data = data;
}
public void setNext(StackNode next) {
this.next = next;
}
}
Stacks: Implementation in JAVA page 36
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackLL.java (similar to LinkedList.java)
public class StackLL {
// top: reference variable to the top
// of the stack (same as "head" of linked list)
private StackNode top;
// CONSTRUCTOR
public StackLL() {
top = null;
}
// MANY methods go here to control the stack
// POP, PUSH, TOP and more...
Stacks: Implementation in JAVA page 37
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackLL.java (similar to LinkedList.java)
 isEmpty() method:
 How would you check if the stack is empty?
 Check if top is equal to null
 Similar to if head == null
//
// boolean | isEmpty()
//
public boolean isEmpty() {
return top == null;
}
Stacks: Implementation in JAVA page 38
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackLL.java (similar to LinkedList.java)
 push() method:
// void | push(int)
public void push(int data) {
top = push(top, data);
}
// StackNode | push(StackNode, int)
private StackNode push(StackNode top, int data) {
// Make a new StackNode with "data" as the data value
// and set the "next" of this new node to the same address as top
// * This is the same as addToFront() method for Linked Lists.
top = new StackNode(data, top);
// Now, return the newly updated top.
return top;
}
Stacks: Implementation in JAVA page 39
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackLL.java (similar to LinkedList.java)
 pop() method:
// StackNode | pop()
public StackNode pop() {
// Save a reference to the current top node
// because we will change where top points to
StackNode temp = top;
// Now, invoke the pop method with top as a parameter.
// This method will return a new top node.
top = pop(top);
// Finally, return temp, which is the previous top node
// that we just "popped" off the list.
return temp;
}
Stacks: Implementation in JAVA page 40
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackLL.java (similar to LinkedList.java)
 pop() method:
//
// StackNode | pop(StackNode)
//
private StackNode pop(StackNode top) {
// Set top equal to the next node.
// This will make top point to the 2nd node instead
// of the first node.
top = top.getNext();
// return the address/reference of the new top node
return top;
}
Stacks: Implementation in JAVA page 41
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 Code for StackLL.java (similar to LinkedList.java)
 top() method:
//
// int | top()
//
public int top() {
// Invoke the top method with top as a parameter
int topValue = top(top);
// return topValue
return topValue;
}
//
// int | top(StackNode)
//
private int top(StackNode top) {
// Return the data value of the top node.
// You can see that we do NOT pop. We are only returning the data value.
return top.getData();
}
Stacks: Implementation in JAVA page 42
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
 Linked Lists Implementation of Stacks:
 The code shown here is only small pieces of the
code.
 Code is on Blackboard:
 You can also view a FULLY-FUNCITONAL Linked-list
Implementation of a Stack on Blackboard.
Stacks: Implementation in JAVA page 43
© Dr. Jonathan (Yahya) Cazalas
Poll: Exit Question
Stacks: Implementation in JAVA page 44
© Dr. Jonathan (Yahya) Cazalas
Poll: Exit Question
Stacks: Implementation in JAVA page 45
© Dr. Jonathan (Yahya) Cazalas
Stacks: Implementation in JAVA
WASN’T
THAT
SPLENDID!
Stacks: Implementation in JAVA page 46
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Stacks:
Implementation in
JAVA

More Related Content

What's hot

Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Jean Carlo Machado
 
Open Close Principle
Open Close PrincipleOpen Close Principle
Open Close PrincipleThaichor Seng
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
 
Different Sorting tecniques in Data Structure
Different Sorting tecniques in Data StructureDifferent Sorting tecniques in Data Structure
Different Sorting tecniques in Data StructureTushar Gonawala
 
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListMarcus Biel
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.CIIT Atd.
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure Janki Shah
 
Insertion sort
Insertion sortInsertion sort
Insertion sortMYER301
 

What's hot (20)

Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Stack project
Stack projectStack project
Stack project
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
 
Circular queue
Circular queueCircular queue
Circular queue
 
Open Close Principle
Open Close PrincipleOpen Close Principle
Open Close Principle
 
Queue
QueueQueue
Queue
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
Different Sorting tecniques in Data Structure
Different Sorting tecniques in Data StructureDifferent Sorting tecniques in Data Structure
Different Sorting tecniques in Data Structure
 
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Circular Queue data structure
Circular Queue data structureCircular Queue data structure
Circular Queue data structure
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
07 java collection
07 java collection07 java collection
07 java collection
 
Queues
QueuesQueues
Queues
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 

Similar to stacks2

Stacks in data structure
Stacks  in data structureStacks  in data structure
Stacks in data structurelodhran-hayat
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
 
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.pdfarpitaeron555
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdfTobyWtf
 
stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxHusnainNaqvi2
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
Data structures and algorithms lab3
Data structures and algorithms lab3Data structures and algorithms lab3
Data structures and algorithms lab3Bianca Teşilă
 
stack in java data structure - muhammed .ppt
stack in java data structure - muhammed .pptstack in java data structure - muhammed .ppt
stack in java data structure - muhammed .pptssusere3b1a2
 
stack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptstack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptssusere3b1a2
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 

Similar to stacks2 (20)

Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
Lec2
Lec2Lec2
Lec2
 
Stacks in data structure
Stacks  in data structureStacks  in data structure
Stacks in data structure
 
104332 sri vidhya eng notes
104332 sri vidhya eng notes104332 sri vidhya eng notes
104332 sri vidhya eng notes
 
stacks1
stacks1stacks1
stacks1
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
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
 
Stack
StackStack
Stack
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdf
 
stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptx
 
Lecture5
Lecture5Lecture5
Lecture5
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
04 stacks
04 stacks04 stacks
04 stacks
 
Lec2
Lec2Lec2
Lec2
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Data structures and algorithms lab3
Data structures and algorithms lab3Data structures and algorithms lab3
Data structures and algorithms lab3
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
 
stack in java data structure - muhammed .ppt
stack in java data structure - muhammed .pptstack in java data structure - muhammed .ppt
stack in java data structure - muhammed .ppt
 
stack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptstack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.ppt
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 

More from Mohamed Elsayed (20)

binary_trees4
binary_trees4binary_trees4
binary_trees4
 
binary_trees3
binary_trees3binary_trees3
binary_trees3
 
binary_trees2
binary_trees2binary_trees2
binary_trees2
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
 
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
 
recursion3
recursion3recursion3
recursion3
 
recursion2
recursion2recursion2
recursion2
 
recursion1
recursion1recursion1
recursion1
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
linked_lists
linked_listslinked_lists
linked_lists
 
sorted_listmatch
sorted_listmatchsorted_listmatch
sorted_listmatch
 
binary_search
binary_searchbinary_search
binary_search
 
introduction
introductionintroduction
introduction
 
heaps2
heaps2heaps2
heaps2
 
heaps
heapsheaps
heaps
 
hash_tables
hash_tableshash_tables
hash_tables
 
graphs
graphsgraphs
graphs
 

Recently uploaded

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Recently uploaded (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

stacks2

  • 1. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Stacks: Implementation in JAVA
  • 2. Stacks: Implementation in JAVA page 2 © Dr. Jonathan (Yahya) Cazalas Stacks – An Overview  Stacks:  Stacks are an Abstract Data Type  Meaning, they are a data type that we must build  (well, in JAVA, we do have a stack class…more on that later)  We must define them and their behaviors  So what is a stack?  A data structure that stores information in the form of a stack.  Consists of a variable number of homogeneous elements  i.e. elements of the same type
  • 3. Stacks: Implementation in JAVA page 3 © Dr. Jonathan (Yahya) Cazalas Stacks – An Overview  Stacks:  Access Policy:  The access policy for a stack is simple: the first element to be removed from the stack is the last element that was placed onto the stack  The main idea is that the last item placed on to the stack is the first item removed from the stack  Known as the “Last in, First out” access policy  LIFO for short  The classical example of a stack is cafeteria trays.  New, clean trays are added to the top of the stack.  and trays are also taken from the top  So the last tray in is the first tray taken out
  • 4. Stacks: Implementation in JAVA page 4 © Dr. Jonathan (Yahya) Cazalas Stacks – An Overview  Stacks:  Basic Operations:  PUSH:  This PUSHes an item on top of the stack  POP:  This POPs off the top item in the stack and returns it  Other important tidbit:  The end of the stack,  where PUSHes and POPs occur,  is usually referred to as the TOP of the stack
  • 5. Stacks: Implementation in JAVA page 5 © Dr. Jonathan (Yahya) Cazalas Stacks – An Overview  Stacks:  Other useful operations:  isEmpty:  Typically implemented as a boolean function  Returns TRUE if no items are in the stack  isFull:  Returns TRUE if no more items can be added to the stack  In theory, a stack should NEVER become full  Actual implementations do have limits on the number of elements a stack can store  top (also called “peek”):  Simply returns the value at the top of the stack without actually popping the stack.
  • 6. Stacks: Implementation in JAVA page 6 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Implementation of Stacks in JAVA:  As discussed on the previous lecture, there are two obvious ways to implement stacks: 1) Using arrays 2) Using linked lists  We will go over both…
  • 7. Stacks: Implementation in JAVA page 7 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Implementation of Stacks in JAVA:  Array:  We will implement the stack as an array!  What does this mean?  This means that when you examine the code for the stack, in fact, it is simply using an array!  So then how is the array a stack? What makes it a stack?  The BEHAVIOR!  We said that an Abstract Data Type is defined based on its behaviors (the operations it can perform).  So we will restrict the behavior of the array.  We will make the array behave like (act like) a stack!
  • 8. Stacks: Implementation in JAVA page 8 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Implementation of Stacks in JAVA:  Array:  So we will restrict the behavior of the array.  We will make the array behave like (act like) a stack!  Example:  With an array, you can insert anywhere or delete anywhere  Insert at the beginning, middle, or end…anywhere!  However:  Since we are making this array behave like (act like) a stack:  We will ONLY allow insertion at the “top”  PUSH  We will ONLY allow deletion at the “top”  POP  So now, our array has basically transformed into a stack!
  • 9. Stacks: Implementation in JAVA page 9 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  What components will we need to store? 1) The array storing the elements  The actual stack of values  What else? 2) An index to the top of the stack  We assume the bottom of the stack is index 0  Meaning, the 1st element will be stored in index 0  and we move up from there 3) The max size of the stack (maxSize)  Of course, we could just use the array.length feature of JAVA to give us the size of the array (which is maxSize)
  • 10. Stacks: Implementation in JAVA page 10 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  Here is our class, StackArray:  maxSize clearly represents the max number of items in the stack  If the stack becomes full, at that point, the top item will be stored at index ‘maxSize-1’ public class StackArray { private int[] stack; private int top; private int maxSize; // Constructor and Methods here }
  • 11. Stacks: Implementation in JAVA page 11 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  Here is the constructor:  So we set maxSize from the parameter size  We then make the new array, stack  Finally, we set top equal to -1  Why? class StackArray { ... public StackArray(int size) { maxSize = size; stack = new int[maxSize]; top = -1; }
  • 12. Stacks: Implementation in JAVA page 12 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  Here is the constructor:  When the stack has one element, what is saved in top?  top is the index to the “top element”  So if there is only one element, that element is at index zero!  So top will have the value, 0, referring to the first cell class StackArray { ... public StackArray(int size) { maxSize = size; stack = new int[maxSize]; top = -1; }
  • 13. Stacks: Implementation in JAVA page 13 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  Here is the constructor:  So when top is zero, that means we have ONE element  How do we show that the stack is empty???  We set top equal to -1  This means that nothing is in the stack. class StackArray { ... public StackArray(int size) { maxSize = size; stack = new int[maxSize]; top = -1; }
  • 14. Stacks: Implementation in JAVA page 14 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  Here are the methods we will need to control our stack behavior:  public boolean isEmpty()  public boolean isFull()  public void push(int j)  public int pop()  public int top()
  • 15. Stacks: Implementation in JAVA page 15 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  isEmpty:  The isEmpty function simply checks if the stack has no elements  Based on what you know thus far, how would you determine if the stack is empty?  If the top currently equals -1!  Here’s the code: public boolean isEmpty() { return (top == -1); }
  • 16. Stacks: Implementation in JAVA page 16 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  isFull:  The isFull function checks to see if the stack is full  How would we do this?  Remember, maxSize is the max # of items in the stack  Item 1 goes at index 0  If the stack is full, the top item will be at index ‘maxSize-1’  Here’s the code: public boolean isFull() { return (top == maxSize-1) }
  • 17. Stacks: Implementation in JAVA page 17 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  push:  Remember, we can only push if the stack is not full  Meaning, if there is room to push  So if the stack is full  We print an error message.  Or throw an Exception, showing the push could not be done  If there is room  We increment top to point to the next space in the stack  Then we simply copy the value into this new top position
  • 18. Stacks: Implementation in JAVA page 18 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  push:  To push an element, increment top to point to the next space in the stack  Then we simply copy the value into this new top position  Here’s the code: public void push(int value) { if (isFull()) System.out.println(“Cannot PUSH; stack is full.”); else stack[++top] = value; }
  • 19. Stacks: Implementation in JAVA page 19 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  pop:  Remember, we can only pop if the stack is not empty  Meaning, there is at least one element to pop  So if the stack is empty  We print an error message  Or throw an exception showing that we cannot pop  If the stack has at least one element:  We return the value at position top  At the same time, we decrement top  This makes the top “pointer” refer to the next item down in the stack
  • 20. Stacks: Implementation in JAVA page 20 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  pop:  To pop an element, we simply return the top item in the stack and then decrement top  Here’s the code: public int pop() { if (isEmpty()) System.out.println(“Cannot POP; stack is empty.”); else return stack[top--]; }
  • 21. Stacks: Implementation in JAVA page 21 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  top (or peek):  The top method is very similar to pop  Remember, we can only check for the top of the stack if the stack is not empty  Meaning, there is at least one element in the stack  So if the stack is empty  We print an error message  If the stack has at least one element:  We simply return the topmost element  But we do NOT decrement
  • 22. Stacks: Implementation in JAVA page 22 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  top:  Simply returns the top item in the stack  Here’s the code: public int top() { if (isEmpty()) System.out.println(“Cannot TOP; stack is empty.”); else return stack[top]; }
  • 23. Stacks: Implementation in JAVA page 23 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Array Implementation of Stacks:  The code shown here is only small pieces of the code.  Code is on Blackboard:  You can also view a FULLY-FUNCITONAL Array Implementation of a Stack on Blackboard.
  • 24. Stacks: Implementation in JAVA page 24 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: HUGE Fail
  • 25. Stacks: Implementation in JAVA page 25 © Dr. Jonathan (Yahya) Cazalas
  • 26. Stacks: Implementation in JAVA page 26 © Dr. Jonathan (Yahya) Cazalas
  • 27. Stacks: Implementation in JAVA page 27 © Dr. Jonathan (Yahya) Cazalas
  • 28. Stacks: Implementation in JAVA page 28 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Implementation of Stacks in JAVA:  Linked-list:  We can also implement the stack as a linked-list!  Advantage of no fixed size and dynamic memory  What does this mean?  This means that when you examine the code for the stack, in fact, it is simply using a modified version of the linked-list code!  So then how is the linked-list a stack?  The BEHAVIOR!  We will restrict the behavior of the linked-list.  We will make the linked-list behave like (act like) a stack!
  • 29. Stacks: Implementation in JAVA page 29 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Implementation of Stacks in JAVA:  Linked-list:  We will restrict the behavior of the linked-list.  We will make the linked-list behave like (act like) a stack!  Example:  With a linked-list, you can insert anywhere or delete anywhere  Insert at the beginning, middle, or end…anywhere!  However:  Since we are making this linked-list behave like a stack:  We will ONLY allow insertion at the “top”  PUSH  We will ONLY allow deletion at the “top”  POP  So now, our linked-list has basically transformed into a stack!
  • 30. Stacks: Implementation in JAVA page 30 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  We essentially use a standard linked list  But we limit the functionality of a linked list  Thus creating the behavior required of a stack  Step 1:  Choose the location of top!  Where should we choose top to be? What is best?  Top could be the “front” of the list OR the “end” of the list  Which is better?  If we choose top to be the end, we must traverse to the end for every PUSH and every POP…a lot of traversing!  BEST choice: we let top be the front of our list.
  • 31. Stacks: Implementation in JAVA page 31 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  So top will refer to the front of our list.  Therefore:  A push is simply inserting into the front of the linked list!  This is the easiest type of insertion  It only requires changing two references!  A pop would be deleting the front node  Again, the easiest type of deletion  Only requiring changing two references!  So, in fact, a linked-list version of a stack is EASIER to code than a regular stack!
  • 32. Stacks: Implementation in JAVA page 32 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  So each node will be an element of the stack  Each node has a data value  Each node also has a next  We simply push (insert at front)  And pop (delete the front node)
  • 33. Stacks: Implementation in JAVA page 33 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  So we will create two classes (like Linked-Lists)  StackNode.java (this is like the LLnode class)  StackLL.java (this is like the LinkedList class)  We use most of the SAME methods as used for the Linked List class  However, we RESTRICT the functionality  Now, we cannot insert anywhere in the list  We can only insert at the top (head)  Now, we cannot delete from anywhere in the list  We can only delete from the top (head)
  • 34. Stacks: Implementation in JAVA page 34 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackNode.java public class StackNode { private int data; private StackNode next; // CONSTRUCTORS public StackNode() { data = 0; next = null; } public StackNode(int data) { this.data = data; next = null; } public StackNode(int data, StackNode next) { this.data = data; this.next = next; }
  • 35. Stacks: Implementation in JAVA page 35 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks: ... // ACCESSORS public int getData() { return data; } public StackNode getNext() { return next; } // MUTATORS public void setData(int data) { this.data = data; } public void setNext(StackNode next) { this.next = next; } }
  • 36. Stacks: Implementation in JAVA page 36 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackLL.java (similar to LinkedList.java) public class StackLL { // top: reference variable to the top // of the stack (same as "head" of linked list) private StackNode top; // CONSTRUCTOR public StackLL() { top = null; } // MANY methods go here to control the stack // POP, PUSH, TOP and more...
  • 37. Stacks: Implementation in JAVA page 37 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackLL.java (similar to LinkedList.java)  isEmpty() method:  How would you check if the stack is empty?  Check if top is equal to null  Similar to if head == null // // boolean | isEmpty() // public boolean isEmpty() { return top == null; }
  • 38. Stacks: Implementation in JAVA page 38 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackLL.java (similar to LinkedList.java)  push() method: // void | push(int) public void push(int data) { top = push(top, data); } // StackNode | push(StackNode, int) private StackNode push(StackNode top, int data) { // Make a new StackNode with "data" as the data value // and set the "next" of this new node to the same address as top // * This is the same as addToFront() method for Linked Lists. top = new StackNode(data, top); // Now, return the newly updated top. return top; }
  • 39. Stacks: Implementation in JAVA page 39 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackLL.java (similar to LinkedList.java)  pop() method: // StackNode | pop() public StackNode pop() { // Save a reference to the current top node // because we will change where top points to StackNode temp = top; // Now, invoke the pop method with top as a parameter. // This method will return a new top node. top = pop(top); // Finally, return temp, which is the previous top node // that we just "popped" off the list. return temp; }
  • 40. Stacks: Implementation in JAVA page 40 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackLL.java (similar to LinkedList.java)  pop() method: // // StackNode | pop(StackNode) // private StackNode pop(StackNode top) { // Set top equal to the next node. // This will make top point to the 2nd node instead // of the first node. top = top.getNext(); // return the address/reference of the new top node return top; }
  • 41. Stacks: Implementation in JAVA page 41 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  Code for StackLL.java (similar to LinkedList.java)  top() method: // // int | top() // public int top() { // Invoke the top method with top as a parameter int topValue = top(top); // return topValue return topValue; } // // int | top(StackNode) // private int top(StackNode top) { // Return the data value of the top node. // You can see that we do NOT pop. We are only returning the data value. return top.getData(); }
  • 42. Stacks: Implementation in JAVA page 42 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA  Linked Lists Implementation of Stacks:  The code shown here is only small pieces of the code.  Code is on Blackboard:  You can also view a FULLY-FUNCITONAL Linked-list Implementation of a Stack on Blackboard.
  • 43. Stacks: Implementation in JAVA page 43 © Dr. Jonathan (Yahya) Cazalas Poll: Exit Question
  • 44. Stacks: Implementation in JAVA page 44 © Dr. Jonathan (Yahya) Cazalas Poll: Exit Question
  • 45. Stacks: Implementation in JAVA page 45 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA WASN’T THAT SPLENDID!
  • 46. Stacks: Implementation in JAVA page 46 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 47. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Stacks: Implementation in JAVA