1 / 7

Stack

Stack. Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations : Push : insert an element at the top of the stack Pop : remove the top element

juan
Download Presentation

Stack

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Stack • Data : • a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed • Main Operations: • Push : insert an element at the top of the stack • Pop : remove the top element • This function does NOT return the top element (because if the stack were empty, the function would be undefined). • Top : return the top element (without removing it) • IsEmpty : return true is empty, false otherwise

  2. Stack • Main characteristics : • LIFO structure: last in, first out • Only the top element may be accessed at any time • The only way to access an element in the middle of the stack is by popping all the elements above it.

  3. Stack • Stacks in the STL: • #include<stack> • There are no iterators (since it is not possible to traverse a stack). stack<int> S; S.push(10); S.push(15); int x = S.top(); if (!S.empty()) S.pop();

  4. Queue • Data : • a collection of homogeneous elements arranged in a sequence. Elements can inserted only at the back and removed only from the front. • Operations: • Enqueue : insert an element at the back • Dequeue : remove an element from the front • Front : return the front element • IsEmpty : return true if empty, false otherwise.

  5. Queue • Main characteristics : • FIFO structure: first in, first out • Only the front element may be accessed at any time • The only way to access an element in the middle of the queue is by removing all the elements before it.

  6. Queue • Implementing our own queue: • Idea 1: Use contiguous memory (an array) • Make the array circular. • Idea 2: Use linked memory • Use a node structure to store the data and a pointer to the next node: create a chain of nodes • Which end of the list is the front of the queue? • The head, since it can be deleted faster than the tail

  7. Queue • Queues in the STL • #include<queue> • no iterators queue<double > Q; Q.push(10.45); Q.push(-6.78); int s = Q.size(); cout << Q.front() << endl; if (!Q.empty()) Q.pop();

More Related