Стеки и очереди 1. Абстрактный стек public interface Stack { static class Underflow extends Exception { public Underflow() { super("Stack underflow");

Slides:



Advertisements
Similar presentations
STACKS & QUEUES. Stacks Abstract data types An abstract data type (ADT) is an abstraction of a data structure An ADT specifies : –Data stored –Operations.
Advertisements

Stacks, Queues, and Linked Lists
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Computer Science 209 Software Development Iterators.
COMP 103 Linked Stack and Linked Queue.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Queues. What is a queue? First-in first-out data structure (FIFO) New objects are placed at rear Removal restricted to front Examples?
Stacks. What is a stack? Last-in first-out data structure (LIFO) New objects are placed on top Removal restricted to top object Examples?
1 Lecture 25 Abstract Data Types –II Overview  A stack Interface in Java  StackEmptyException  Stack ADT(A Simple Array-Based Implementation  Queue.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
1 Lecture 26 Abstract Data Types –III Overview  Creating and manipulating Linked List.  Linked List Traversal.  Linked List Traversal using Iterator.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Singly Linked Lists - Ed. 2, 3: Chapter 4 - Ed. 4.: Chapter 3.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Stacks, Queues, and Deques
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
1 Helmut Schauer Educational Engineering Lab Department for Informatics University of Zurich Listen, Stacks und Queues headtail p x.
Stacks, Queues, and Deques
Data Structures - Queues
Chapter 7 Stacks II CS Data Structures I COSC 2006
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
Stacks and Linked Lists. Abstract Data Types (ADTs) An ADT is an abstraction of a data structure that specifies – Data stored – Operations on the data.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
Dr. Salah Hammami KSU-CCIS-CS Ahmad Al-Rjoub CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Chapter.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
1 Stacks and Queues Starring: IndexOutOfBOundsException Co-Starring: NoSuchElementException.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
LinkedList Many slides from Horstmann modified by Dr V.
Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Абстрактные типы данных 1. Абстрактная дата Date dt1, dt2; dt1 = new Date(1, Date.MARCH, 2006); dt2 = (Date)dt1.clone(); dt2.add(300); //
Computer Science 209 Software Development Inheritance and Composition.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
CSCI 62 Data Structures Dr. Joshua Stough October 7, 2008.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
Object Oriented Programming in Java Habib Rostami Lecture 7.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Sections 3.4 Formal Specification
Elementary Data Structures
QueueStack CS1020.
Linked List Stacks, Linked List Queues, Dequeues
Week 3 - Friday CS221.
Stacks.
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Stacks.
Lecture 21 Stacks and Queues Richard Gesick.
null, true, and false are also reserved.
ساختمان داده ها پشته ها Give qualifications of instructors: DAP
Stacks public interface Stack { public boolean empty();
More Data Structures (Part 1)
Lecture 16 Stacks and Queues CSE /26/2018.
Stacks.
Stacks, Queues, and Deques
Lecture 16 Stacks and Queues CSE /26/2018.
Data Structures and Algorithms 2/2561
CHAPTER 3: Collections—Stacks
Presentation transcript:

Стеки и очереди 1. Абстрактный стек public interface Stack { static class Underflow extends Exception { public Underflow() { super("Stack underflow"); } }; void push(Object element); Object pop() throws Underflow; Object peek() throws Underflow; boolean empty(); } top

2. Абстрактная очередь public interface Queue { static class Underflow extends Exception { public Underflow() { super(“Queue underflow"); } }; void enqueue(Object element); Object dequeue() throws Underflow; Object head() throws Underflow; Object tail() throws Underflow; boolean empty(); } headtail

Различные подходы к реализации стека public interface List { // Elements counting boolean isEmpty(); int size(); // Access to elements Object first(); Object last(); // Changes in list Object addFirst(Object o); Object addLast(Object o); Object removeFirst(); Object removeLast(); // List iteration void iterate(Visitor visitor); Iterator iterator(); } public abstract class MyStack implements List, Stack { boolean empty() { return isEmpty(); } Object peek() { return first(); } Object push(Object o) { return addFirst(o); } Object pop() { return removeFirst(); } } public abstract class AbstractStack implements Stack { private List list; public AbstractStack(List list) { this.list = list; } public boolean isEmpty() { return list.isEmpty(); } public Object push(Object o) { return list.addFirst(o); } public Object pop() { return list.removeFirst(); } public Object peek() { return list.first(); } } public class LinkedStack extends AbstractStack { public LinkedStack() { super(new LinkedList()); } }

Реализация стека в виде массива public class ArrayStack implements Stack { private Object[] stack; // Массив стековых элементов private int topPtr; // Число элементов в стеке - указатель вершины static class Underflow extends Exception { public Underflow() { super("Stack underflow"); } } public ArrayStack(int maxElems) { stack = new Object[maxElems]; topPtr = 0; } public ArrayStack() { this(100); } public boolean empty() { return topPtr == 0; } public Object push(Object element) { if (topPtr == stack.length) throw new Overflow(); return stack[topPtr++] = element; } public Object peek() throws Underflow { if (topPtr == 0) throw new Underflow(); return stack[topPtr-1]; } public Object pop() throws Underflow { if (topPtr == 0) throw new Underflow(); return stack[--topPtr]; }

Реализация пары стеков в массиве public class StackPair { private Object[] stack; int ptr1, ptr2; public StackPair(int max) { stack = new Object[max]; ptr1 = 0; ptr2 = stack.length-1; } public StackPair() { this(100); } Object push1(Object element) throws Stack.Overflow { if (ptr1 > ptr2) throw new Stack.Overflow(); return stack[ptr1++] = element; } Object push2(Object element) throws Stack.Overflow { if (ptr1 > ptr2) throw new Stack.Overflow(); return stack[ptr2--] = element; }... boolean empty1() { return ptr1 == 0; } boolean empty2() { return ptr2 == stack.length-1; } } ptr1 ptr2

Очередь с приоритетами public interface Prioritized { int getPrio(); void setPrio(int prio); } public class PrioQueue implements Queue { Object enqueue(Object element) {...} Object dequeue() throws Underflow {...} Object head() throws Underflow {...} Object tail() throws Underflow { throw new RuntimeException("tail: no implementation"); } boolean empty() {...} Prioritized setPrio(Prioritized obj, int prio) } Пирамида – один из возможных способов реализации очереди с приоритетами:

Применение стеков для анализа выражений 1. Проверка правильности расстановки скобок. 1 + (a + b) * (2 – (c – d) * (a + b)) a[i+1] * (2 – c[i–1] * (a[i] + 1)) []() [] () [] ()

public static boolean parentheses(String openBrackets, String closeBrackets, String source) { Stack pars = new LinkedStack(); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); // 1. Проверка открывающей скобки int j = openBrackets.indexOf(c); if (j >= 0) { pars.push(new Character(closeBrackets.charAt(j))); continue; } // 2. Проверка закрывающей скобки j = closeBrackets.indexOf(c); if (j >= 0) { try { if (!pars.pop().equals(new Character(c))) return false; } catch (Stack.Underflow u) { return false; } return pars.empty(); } Реализация анализа правильности расстановки скобок

Перевод выражения в обратную польскую запись 1 + (a + b) * (2 – (c – d) * (a + b)) 1 a b + 2 c d – a b + * – * + 1 ab2 c da b + + * - - * + Loadc 1 Load a Load b Add Loadc 2 Load c Load d Sub Load a Load b Add Mult Sub Mult Add 1 a b a+b 2 c d c-d a b a+b (c-d)*(a+b) 2-(c-d)*(a+b) (a+b)* (2-(c-d)*(a+b)) 1+(a+b)* (2-(c-d)*(a+b))

Алгоритм анализа выражения 1 + (a + b) * (2 – (c – d) * (a + b)) Для каждой из лексем: - если это первичное, выводим его; - если это ‘(‘, кладем ее в стек; - если это операция, выводим не менее приоритетные и кладем ее знак в стек; - если это ‘)’, выводим операции до знака ‘(‘ и вычеркиваем скобку из стека. В конце работы выводим все операции из стека. 1ab+2cd–ab+ * – * ( ( ( ( * *