90 likes | 325 Views
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
E N D
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
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.
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();
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.
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.
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
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();