Vous êtes sur la page 1sur 50

Week 4 : Stack

STIA2024
Data Structures & Algorithm
Analysis

1
Lecture Outline

 Stack
 Using an array
 Using linked list
 Applications

2
Learning Objective
 To elaborate the concepts of stack,
 To apply the concept of stack in programming,

3
Stack
 Additions are made to one end, the top
 The item most recently added is always on the top
 Most commonly used in computer science world,
especially by many algorithms (E.g.: compiler, run-time
environment)
 Analogy:

4
Stack
 More restrictive data structure because client can
access only a single element at topmost of the stack.
 A stack is a data structure in which only the top
element can be accessed.
 Storing a data item in a stack is called pushing it onto
the stack
 Removing a value from a stack is called popping the
stack
 A stack is a container for an object in which the insert
and remove process will happen at one end called as
top
 Concepts : Last In First Out (LIFO)

5
Item removed items added at
from this end only this end only

The end to which


newest item items are added or
removed is referred
: as top
:
:
:
:
:
oldest item
Uses of stacks
 Stacks are much used in computers, especially in
 storing data during method calls
 recursive processes (as in functional programming)
 calculating the value of expressions
 We usually write expressions using infix operators:
 a*b–c
 Infix expressions are evaluated on computer in two
stages:
 they are converted into reverse Polish (postfix):
 ab*c–
 the reverse Polish notation is evaluated
 Both stages involve the use of a stack
 Computers, as we know them, would hardly work at all
without stacks
Basic Operations in Stack
 Create an empty stack
 Determine the stack is full or empty
 Remove item/object from the top stack (POP)
 Insert new item/object at the top of stack. (PUSH)
 Access item/object at the top of stack (PEEK)
 Determine the size of stack
Visit this site for demo: http://www2.hig.no/~algmet/animate.html
ADT Stack
Abstract Data Types (ADT) is a group of object
that consist of some operations.
 The operations are as below:
• stack constructor – instantiate stack as empty
• isEmpty() – Tests if a stack is empty.
Return true/false .
ADT Stack
• peek() – Looks at the object at the top of the
stack without removing it from the
stack.
• push(item) – Pushes an item onto the top of the
stack
• pop() – Removes the object at the top of the
stack. Error message is display if stack
is empty.
• size() – Returns the current number of items
in the stack
ADT Stack Specifications
Data Field Attribute
Node top A reference to the top of the stack
Methods Behavior
void push(Object) Place the argument at the top of the stack
Object pop() Retrieve and remove object at the top of the stack
Object peek() Retrieve object at the top of stack without removal
boolean isEmpty() Returns true if stack is empty
; false if not empty.

 Java class library provide java.util.Stack


package in order to implement the method in
ADT stack operations.
ADT Stack - Illustration

A stack of strings after (a) push adds Jim;


(b) push adds Jess; (c) push adds Jill; (d) push adds Jane; (e)
push adds Joe; (f) pop retrieves and removes Joe; (g) pop
12
retrieves and removes Jane
Implementing a stack

 We could use an array. Characteristically, an


array has a limited size, so such a stack would
be bounded by the size of the array
 We could use a linked list. Such a stack would,
in normal practice, be unbounded (or bounded
only by the physical limits of the machine we're
working on).
Stack using arrays
 The implementation of bounded stack is same as
the implementation of array.

 Assume the declaration of array as below


int [ ] Stack = new Stack[8]

 Therefore:
 Stack[0]  for the lowest item (bottom)
 Stack[7]  for the top item
Stack using arrays
• An integer variable top tells us which is the top element.

Push 7
5 12 5 12 7

Pop returns 7
top top

Problem: Cannot hold more than 4 elements


Stack using arrays

 An integer variable “top” is assumed as a counter.


 Counter “top” must be initialized with –1 for an empty stack.
 Adding data, counter must be increased by 1
 Removing data, counter must be decreased by 1

16
Stack using arrays
push()
the top counter will increase by 1 for each time the item was inserted
into the stack.
current stack after push()
3 3
2 top = 2 2 30
top = 1 1 20 1 20
0 10 0 10

pop()
the top counter will decrease by 1 for each time the item was removed
from the stack. current stack after pop()
3 3
top = 2 2 30 2
1 20 top = 1 1 20
0 10 0 10
Stack using arrays
3 3 3
2 2 2
1 1 top = 1 1 3
top = -1 0 top= 0 0 1 0 1

empty stack push(1) push(3)

3 3 3
top =2 2 8 2 top = 2 2 7
1 3 top = 1 1 3 1 3
0 1 0 1 0 1

push(8) a= pop() push(7)


Stack using arrays – common
operations
1. Create empty stack the implementation is
2. Determine empty stack similar with Contiguous List

3. Remove item from top of stack (POP)


4. Insert item into stack (PUSH)
5. Access item at the top of stack (PEEK)
6. Determine the current size of stack.
Stack using arrays

 Determine whether the stack is full or not before performing


push() operation.

 Determine whether the stack is empty or not before performing


pop() operation.

 To access the lower item in the stack, the top item should be removed
until the item is found.

 If an item in an empty stack is remove, a stack underflow message


should be display. (use EmptyStackException in
java.util.EmptyStackException)
Stack using arrays - Remove
item/object from Stack (POP)

public Object pop()


{
if (itemNum==0)
System.out.println (“Empty Stack”);
throw new EmptyStackException();
else
return stack[--itemNum]
}

**Object – can be data primitive type such as (int, double, char,


float etc.) OR object
Stack using arrays - Insert
item/object into Stack (PUSH)

public void push(Object newItem)


{
if (itemNum ==stack.length)
System.out.println (“Stack Full”)
else{
stack[itemNum]=newItem;
itemNum ++;}
}

**Object – can be data primitive type such as (int, double, char,


float etc.) OR object
Stack using arrays - Access
item/object at top of Stack (PEEK)

public Object peek()


{
if (itemNum ==0){
System.out.println (“Empty stack”);
throw new EmptyStackException();
}
else
return stack[itemNum -1]
}

**Object – can be data primitive type such as (int, double, char,


float etc.) OR object
Stack using arrays – Determine
Stack Size (SIZE)

public Object size()


{
return itemNum;
}

**Object – can be data primitive type such as (int, double, char,


float etc.) OR object
Stack using linked list
 When using a chain of linked nodes to implement a stack
 The first node should reference the stack's top

A chain of linked nodes that implements a stack. 25


Stack using linked list

(a) A new node that references the top of the stack; (b) the new node
is now at the top of the stack.
26
Stack using linked list
 Before creating a stack, pointer “top” must be initialized to
“null”.
 It means the stack is empty

27
Stack using chain of linked nodes
 The concept is same as linked list.
 Each node is a item/object in stack.
 The implementation using 2 classes:
1. Node class
2. StackList class
Stack using chain of linked nodes
 The declarations of class Node:
/* Node.java Authors: Koffman & Wolz
* Represents a node with information and link fields.
*/
class Node
{
// Data fields for Node
private Object info; // data stored in the node
private Node link; // link to next node
// Methods
// Constructors
// postcondition: Creates a new empty node.
public Node() {
info = null;
link = null;
}
// postcondition: Creates a new node storing obj.
public Node(Object obj) {
info = obj;
link = null;
}
// postcondition: Creates a new node storing obj
// and linked to node referenced by next.
public Node(Object obj, Node next) { ***Object – can be
info = obj;
link = next; primitive data type
}
(int,double, char, Float
dll) or Object
Stack using chain of linked nodes
 The declarations of class Node:

// accessors
public Object getInfo()
{
return info;
}
public Object getLink()
{
return link;
}

// mutators
public void setInfo(Object newInfo)
{
info = newInfo;
}
public void setLink(Node newLink)
{
link = newLink;
}
}
Class StackList
public class StackList {
// Data fields
private Node top; // reference to
// top of stack
// Methods
public StackList() {
top = null; // new stack is empty
}
/* push - pushes an item onto a stack
* postcondition: item is at the top of the stack
*/
public void push(Object item) {
//Allocate a new node, store item in it, and
// link it to old top of stack.
top = new Node(item, top);
}

/* postcondition: Returns item at top of stack and


* removes it. Throws an exception if stack is empty.
*/
public Object pop() {
Object item = peek(); // Retrieve item at top
//Remove old top of stack
top = top.getLink(); // Link top to second element
31
return item; // Return data at old top
}
Class StackList, cont...
/* peek - retrieves an item from a stack
* postcondition: Returns item at top of stack without
* removing it. Throws an exception if stack is empty.
*/
public Object peek() {
if (isEmpty())
throw new NullPointerException();
return top.getInfo(); //return top item
}

/* isEmpty - tests whether a stack is empty


* postcondition: returns true if stack is empty;
* otherwise, returns false.
*/
public boolean isEmpty() {
return (top == null);
}
} // class StackList

32
Stack - Removing node
 Algo.
 Retrieve item at top
 Remove item at top of stack – link top to second element
 Return item at top of stack

 code
public Object pop() {
Object item = peek(); // Retrieve item at top
//Remove old top of stack
top = top.getLink(); // Link top to second element
return item; // Return data at old top
}
Stack - Removing node
 Use this statement
top = top.getLink() // top = top.link

X 2 4 5 7
top

4 5 7
top

remove 2 34
Stack - Inserting a node
 Algo.
 If stack is empty
 Set pointer “top” to new node
 else
 Set pointer “link” of new node to the first node
 Set pointer “top” to the new node
.

top

2
newNode
35
Stack - Inserting a node:empty list
 code
Node newNode = new Node(new Integer(8))
if (top == null)
top = newNode;
else {
newNode.setLink(top); // newNode.link = top
top = newNode;
}
count++;
top = newNode

X 8
top
newNode
8
top
36
Insert 8
Stack-Inserting a node:non empty
list
 code
Node newNode = new Node(new Integer(7))
if (top == null)
top = newNode;
else {
newNode.setLink(top); // newNode.link = top
top = newNode;
}
count++;

X 8
top
top = newNode newNode.link = top
7 X
newNode
7 8
top 37

Insert 7
Java Collections Framework
 Java 2 provides various classes that implement
abstract data types involving collections of
elements, such as lists, stacks and sets.
 These are in the java.util package , and are
known as the Java Collections Framework.
 The framework contains interfaces, which can be
considered to be specifications of abstract data
types; abstract classes, which implement some
methods, but not all; and classes which fully
implement all methods. The following chart shows
the main components of the Collections
Framework.
Java Collections Framework
A collection can be a set or a list,
defined in the interfaces Set and
List, which are sub-interfaces of
Collection. AbstractSet TreeSet

HashSet

Set SortedSet

AbstractCollection Collection

List

AbstractList ArrayList LinkedList Vector Stack

AbstractSequentialList
The Stack Class
Vector The Stack class
represents a last-in-first-
out stack of objects. The
Stack elements are accessed
+empty() : boolean only from the top of the
+peek() : Object
+pop() : Object stack. You can retrieve,
+push(element: Object) : void
+search(element: Object) : int insert, or remove an
element from the top of
the stack.
Example
import java.util.Stack;
public class StackExample {
public static void main(String args[]) {
Stack s = new Stack();
s.push("Ali");
s.push("Siti");
s.push("Zila");

System.out.println("Top of Stack : " + s.peek());


s.pop();
Output
System.out.println("After pop, top of stack is : " + s.peek());
s.push("Mohamad");
s.push("Hafiz"); Top of Stack : Zila
After pop, top of stack is :
int count = s.size(); Siti
while (count != -1 && count > 0) {
Hafiz
System.out.println(s.pop()); Mohamad
count--; Siti
} Ali
}
}
References
 Data Structures and Abstractions with Java . Authors: Frank M.
Carrano & Walter Savitch . Chapter 20, 21, 22 & 23
 Problem Solving with Java. Authors: Elliot B. Koffman & Ursula
Wolz. Chapter 10.
 Data Structures & Other Objects Using Java. Author: Michael Main
Chapter 6 & 7
 Liang, D. (2005). Introduction To Java Programming.
Comprehensive Version. Prentice Hall.
 Palmer, B. Data Structure And Algorithm 1. Retrieved from
http://www.macs.hw.ac.uk/~bpalmer/DSA1/Lectures/Week%201%20Stack
.ppt.

42
Conclusion

Q & A Session

43
Example (full code) – Stack
using chain of linked nodes
class Node {
// Data fields for Node
private Object info; // data stored in the node
private Node link; // link to next node

// Constructors
public Node(Object obj) {
info = obj;
link = null;
}
// postcondition: Creates a new node storing obj and linked to node
//referenced by next.
public Node(Object obj, Node next) {
info = obj;
link = next;
}
// accessors
public Object getInfo() {
return info;
}
public Object getLink() {
return link;
}
// mutators
public void setInfo(Object newInfo) {
info = newInfo;
}
public void setLink(Node newLink) {
link = newLink;
}
} //class node
import java.io.*;
import java.util.EmptyStackException;
public class StackList {
// Data fields
private Node top; // reference to top of stack
private int itemNum;

// Methods
public StackList() {
top = null; // new stack is empty
itemNum=0;
}

/* push - pushes an item onto a stack postcondition: item is at the top of the
stack*/
public void push(Object item) {
//Allocate a new node, store item in it, and
// link it to old top of stack.
top = new Node(item, top);
itemNum++;
}

/* postcondition: Returns item at top of stack and emoves it. Throws an


exception if stack is empty.*/
public Object pop() {
Object item = peek(); // Retrieve item at top
//Remove old top of stack
top = top.getLink(); // Link top to second element
itemNum--;
return item; // Return data at old top
}
/* peek - retrieves an item from a stack postcondition: Returns item at top of
stack without removing it. Throws an exception if stack is empty.*/
public Object peek() {
if (isEmpty())
throw new EmptyStackException();
return top.getInfo(); //return top item
}

/* isEmpty - tests whether a stack is empty postcondition: returns true if


stack is empty; otherwise, returns false.*/
public boolean isEmpty() {
return (top == null);
}

/* size - retrieves stack size*/


public boolean size() {
return itemNum;
}

/* display - displays stack elements*/


public void display() {
Nod current;
System.out.print("\ntop -->");
for(current= top; current != null; current = current.getLink())
System.out.print(current.getInfo()+"-->");
System.out.println("null");
}
public static void main(String[] arg) {
StackList stack = new StackList();

stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.display();
System.out.println("Top Item = "+ stack.peek());
System.out.println("Stack size = "+ stack.size());
System.out.println("\nItem removed = "+ stack.pop());
System.out.println("Item removed = "+ stack.pop());
stack.display();
System.out.println("Item at top of stack = "+ stack.peek());
System.out.println("Stack size = "+ stack.size());

}
} // class StackList
Output

top -->50-->40-->30-->20-->10-->null
Top Item = 50
Stack size = 5

Item removed = 50
Item removed = 40

top -->30-->20-->10-->null
Item at top of stack = 30
Stack size = 3 Process Exit...
Exercise –Tracing for output
import java.util.Stack;
public class StackExample {
public static void main(String args[]) {
Stack myStack = new Stack();
myStack.push (16);
myStack.push (8);
myStack.push (20);
myStack.push (3);
System.out.println("The top element of myStack: " +
myStack.peek());
myStack.pop();
System.out.println("After the pop operation, the top element of
myStack: " + myStack.peek());
System.out.println("myStack elements:");
while (!myStack.isEmpty()){
System.out.print(myStack.peek()+ " ");
myStack.pop();
}
}
}

Vous aimerez peut-être aussi