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

stacks2

  • 1.
    College of Computing& Information Technology King Abdulaziz University CPCS-204 – Data Structures I Stacks: Implementation in JAVA
  • 2.
    Stacks: Implementation inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA page 24 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: HUGE Fail
  • 25.
    Stacks: Implementation inJAVA page 25 © Dr. Jonathan (Yahya) Cazalas
  • 26.
    Stacks: Implementation inJAVA page 26 © Dr. Jonathan (Yahya) Cazalas
  • 27.
    Stacks: Implementation inJAVA page 27 © Dr. Jonathan (Yahya) Cazalas
  • 28.
    Stacks: Implementation inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA 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 inJAVA page 43 © Dr. Jonathan (Yahya) Cazalas Poll: Exit Question
  • 44.
    Stacks: Implementation inJAVA page 44 © Dr. Jonathan (Yahya) Cazalas Poll: Exit Question
  • 45.
    Stacks: Implementation inJAVA page 45 © Dr. Jonathan (Yahya) Cazalas Stacks: Implementation in JAVA WASN’T THAT SPLENDID!
  • 46.
    Stacks: Implementation inJAVA 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