Docsity

Stacks - Advanced Programming - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download Stacks - Advanced Programming - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

Abstract Data Types

Stacks

Abstract Data Type Defined

Sedgewick Definition 4.1:

An abstract data type ( ADT ) is a data type (a set of values and a

collection of operations on those values) that is accessed only

through an interface. We refer to a program that uses an ADT as a

client , and a program that specifies the data type as an

implementation.

The key distinction that makes a data type abstract is the word

only. Client programs never access data except through the

operations provided in the interface. We say that the interface is

opaque. The client cannot see the implementation through the

interface. This is also called encapsulation.

Pushdown-stack

• Stack model

  • A stack is a list with the restriction that insertion & deletion can be

performed only at the end (or top) of the list.

  • Only the top node is accessible: New nodes can be added and removed only

at the top

  • Last-in, first-out (LIFO)
  • Bottom of stack indicated by a link member to NULL

• push

  • Adds a new node to the top of the stack

• pop

  • Removes a node from the top
  • Stores the popped value
  • Returns true if pop was successful
    • A stack can be empty, “pop” from an empty stack is an error
    • A stack can never be full (assuming infinite memory) S4 top S S S (^4) top 1 3 6

1 3 6 top Push (4)

Pop (4) 1 3 6 top

Pushdown-stack ADT interface

template

class STACK

private:

// Implementation-dependent code

public:

STACK(int);

int empty() const;

void push(Item item);

Item pop();

Linked-list implementation of a pushdown stack

template class STACK { private: struct node { Item item; node* next; node(Item x, node* t) { item = x; next = t; } }; typedef node *link; link head; public: STACK(int) { head = 0; } int empty() const { return head == 0; } void push(Item x) { head = new node(x, head); } Item pop() { Item v = head->item; link t = head->next; delete head; head = t; return v; } }; We can implement the push and pop operations for the pushdown stack ADT in constant time, using either arrays or linked lists.