The document discusses stacks and queues as data structures. It describes stacks as lists where insertion and deletion occur at the same end, following LIFO order. The primary stack operations are push and pop. Stacks can be implemented using arrays or linked lists. Queues are lists where insertion occurs at one end and deletion at the other, following FIFO order. The primary queue operations are enqueue and dequeue. Queues can also be implemented using arrays or linked lists. Examples of stack and queue implementations and uses are provided.
From Functor Composition to Monad TransformersHermann Hueck
In a List[Option[A]] or Future[Option[A]] we want to access the value of type A conveniently without nested mapping and flatMapping.
We can avoid nested mapping with composed Functors. Functors compose, but Monads do not! What can we do?
Monad transformers to the rescue!
After going through Functor composition I show how 2 Monads are bolted together with a Monad transformer and how to use this construct. I demonstrate this with the Option transformer OptionT and will end up with best practices.
From Functor Composition to Monad TransformersHermann Hueck
In a List[Option[A]] or Future[Option[A]] we want to access the value of type A conveniently without nested mapping and flatMapping.
We can avoid nested mapping with composed Functors. Functors compose, but Monads do not! What can we do?
Monad transformers to the rescue!
After going through Functor composition I show how 2 Monads are bolted together with a Monad transformer and how to use this construct. I demonstrate this with the Option transformer OptionT and will end up with best practices.
A bird's eye view on some programming languages, focusing on concepts like typing, execution model or style. Presented on T3chFest 2016 in Leganés, Madrid, Spain.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
Gary Bernhardt’s famous WAT talk pokes fun at the weird things in Ruby and JavaScript due to weak typing and operator overloading. But Go can be strange, too. It has its own odd behaviors, some of which we run into every day. Learning about Go’s corner cases teaches us how Go works under the covers.
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftTomohiro Kumagai
Swift 3.0 で変わったところから、興味の湧いた 13 項目を、自分が開催する "カジュアル Swift 勉強会" の紹介も兼ねつつ、Swift 愛好会で発表してきました。
少し前に iPhone Dev Sapporo 勉強会で話した内容から、項目数は減らしつつも、新たな項目を紹介したり、紹介済みの項目についても内容を少し膨らませたりしています。
For more information about https://www.zricks.com/Kalpataru-Immensa-Thane-West-Mumbai/15292
Kalpataru Immensa, Thane West, Mumbai. Visit: http://www.zricks.com
Prestige Augusta Golf Village Brochure - Zricks.comZricks.com
For more information about http://www.zricks.com/Prestige-Augusta-Golf-Village-Horamavu-Bangalore/14198
Prestige Augusta Golf Village, Horamavu, Bangalore. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Skylark-Arcadia--Whitefield-Bangalore/14306
Skylark Arcadia, Whitefield, Bangalore. Visit: http://www.zricks.com
For more information about Prestige Bagamane Temple Bells, Raja Rajeshwari Nagar, Mysore Road, Bangalore – Zricks.com
Prestige Bagamane Temple Bells, Rajeshwari Nagar, Bangalore. Visit: http://www.zricks.com
A bird's eye view on some programming languages, focusing on concepts like typing, execution model or style. Presented on T3chFest 2016 in Leganés, Madrid, Spain.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
Gary Bernhardt’s famous WAT talk pokes fun at the weird things in Ruby and JavaScript due to weak typing and operator overloading. But Go can be strange, too. It has its own odd behaviors, some of which we run into every day. Learning about Go’s corner cases teaches us how Go works under the covers.
Swift 3.0 で変わったところ - 厳選 13 項目 #love_swift #cswiftTomohiro Kumagai
Swift 3.0 で変わったところから、興味の湧いた 13 項目を、自分が開催する "カジュアル Swift 勉強会" の紹介も兼ねつつ、Swift 愛好会で発表してきました。
少し前に iPhone Dev Sapporo 勉強会で話した内容から、項目数は減らしつつも、新たな項目を紹介したり、紹介済みの項目についても内容を少し膨らませたりしています。
For more information about https://www.zricks.com/Kalpataru-Immensa-Thane-West-Mumbai/15292
Kalpataru Immensa, Thane West, Mumbai. Visit: http://www.zricks.com
Prestige Augusta Golf Village Brochure - Zricks.comZricks.com
For more information about http://www.zricks.com/Prestige-Augusta-Golf-Village-Horamavu-Bangalore/14198
Prestige Augusta Golf Village, Horamavu, Bangalore. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Skylark-Arcadia--Whitefield-Bangalore/14306
Skylark Arcadia, Whitefield, Bangalore. Visit: http://www.zricks.com
For more information about Prestige Bagamane Temple Bells, Raja Rajeshwari Nagar, Mysore Road, Bangalore – Zricks.com
Prestige Bagamane Temple Bells, Rajeshwari Nagar, Bangalore. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Prestige-Edwardian-Vasanth-Nagar-Bangalore/14234
Prestige Edwardian, Vasanth Nagar, Bangalore. Visit: http://www.zricks.com
For more information about https://www.zricks.com/Goyal-Orchid-Whitefield-Whitefield-Bangalore/15129
Goyal Orchid Whitefield, Whitefield, Off Whitefield Main Road, Bangalore. Visit: http://www.zricks.com
For more information about https://www.zricks.com/Divyasree-77-East-Marathahalli-Bangalore/15466
Divyasree 77 East, Marathahalli, Marathahalli Road, Bangalore. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Peninsula-Heights-JP-Nagar-Bangalore/14364
Peninsula Heights, JP Nagar, Marenahalli Road, Bangalore. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Majestique-Imperia-Fursungi-Pune/14431
Majestique Imperia, Fursungi, Fursungi Bhekrai Road, Pune Visit: http://www.zricks.com
For more information about http://www.zricks.com/Indiabulls-Greens-Panvel-Navi-Mumbai/14256
Indiabulls Greens, Panvel, MBT Road, Navi Mumbai. Visit: http://www.zricks.com
For more information about https://www.zricks.com/Gera's-Isle-Royale-Bavdhan-Pune/15475
Gera's Isle Royale, Bavdhan, Mulshi Road, Pune. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Rustomjee-Urbania-Thane-East-Mumbai/14436
Rustomjee Urbania, Thane East, Eastern Express Highway, Mumbai Visit: http://www.zricks.com
For more information about http://www.zricks.com/Assetz-63-East-Sarjapur-Bangalore/14372
Assetz 63 East, Sarjapur, Off Sarjapur Road, South East, Bangalore. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Lakhani-Panache-Lonavala-Pune/14324
Lakhani's Panache Dream Villas, Lonavla, Mumbai. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Mantra-Senses-Undri-Pune/14398
Mantra Senses, Undri, Katraj Bypass Road, Pune. Visit: http://www.zricks.com
For more information about http://www.zricks.com/Rohan-Jharokha-2-Bellandur-Bangalore/15080
Rohan Jharoka 2, Bellandur, Bangalore. Visit: http://www.zricks.com
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
1. The design of a singly-linked list
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define defaultSize 100
void Assert(bool val, string s)
{
if (!val)
{ // Assertion failed -- close the program
cout << "Assertion Failed: " << s << endl;
exit(-1);
}
}
template <typename E>
class Link {
public:
E element; // Value for this node
Link *next; // Pointer to next node in list
// Constructors
Link(const E& elemval, Link<E>* nextval = NULL)
{ element = elemval; next = nextval; }
Link(Link<E>* nextval =NULL) { next = nextval; }
};
template <typename E>
class LList: public Link<E> {
private:
Link<E>* head;// Intialization helper method
Link<E>* tail;// Pointer to last element
Link<E>* curr;// Access to current element
int cnt;// Size of list
void init(){// Intialization helper method
curr = tail = head = new Link<E>;
cnt = 0;
}
void removeall() {// Return link nodes to free store
while(head != NULL) {
curr = head;
head = head->next;
delete curr;
}
}
public:
LList(int size=defaultSize) { init(); }// Constructor
~LList() { removeall(); }// Destructor
void print() const;// Print list contents
void clear() { removeall(); init(); }// Clear list
// Insert "it" at current position
void insert(const E& it) {
curr->next = new Link<E>(it, curr->next);
if (tail == curr) tail = curr->next; // New tail
cnt++;
}
void append(const E& it) { // Append "it" to list
tail = tail->next = new Link<E>(it, NULL);
cnt++;
}
// Remove and return current element
E remove() {
Assert(curr->next != NULL, "No element");
E it = curr->next->element; // Remember value
Link<E>* ltemp = curr->next; // Remember link node
if (tail == curr->next) tail = curr; // Reset tail
curr->next = curr->next->next; // Remove from list
delete ltemp; // Reclaim space
cnt--; // Decrement the count
return it;
}
void moveToStart()// Place curr at list start
{ curr = head; }
void moveToEnd() // Place curr at list end
{ curr = tail; }
void prev(){
if (curr == head) return;
Link<E>* temp = head;
while (temp->next!=curr) temp=temp->next;
curr = temp;
}
void next(){ if (curr != tail) curr = curr->next; }
int length() const { return cnt; }
int currPos() const {
Link<E>* temp = head;
int i;
for (i=0; curr != temp; i++)
temp = temp->next;
return i;
}
void moveToPos(int pos){
Assert ((pos>=0)&&(pos<=cnt), "Position out of range");
curr = head;
for(int i=0; i<pos; i++) curr = curr->next;
}
const E& getValue() const {
Assert(curr->next != NULL, "No value");
return curr->next->element;
}
};
completed this code to fulfill the requirement below:
Write a function to insert an integer into a singly-linked list of elements arranged from largest to
smallest. Requires that elements remain ordered after insertion.
2. The design of array-based stack
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string.h>
#.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
Write a program that converts an infix expression into an equivalent postfix expression. The
rules to convert an infix expression into an equivalent postfix expression are as follows (C++):
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
Turn in:
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program. (C++)
(Below already done code.)
//Header file: myStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
#include \"stackADT.h\"
using namespace std;
template
class stackType: public stackADT
{
public:
const stackType& operator=(const stackType&);
//Overload the assignment operator.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: stackTop = 0
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postc.
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
New folder/jsjf/ArrayStack.classpackage jsjf;
publicsynchronizedclass ArrayStack implements StackADT {
privatestaticfinal int DEFAULT_CAPACITY = 100;
private int top;
private Object[] stack;
public void ArrayStack();
public void ArrayStack(int);
public void push(Object);
private void expandCapacity();
public Object pop() throws exceptions.EmptyCollectionException;
public Object peek() throws exceptions.EmptyCollectionException;
public int size();
public boolean isEmpty();
public String toString();
}
New folder/jsjf/ArrayStack.javaNew folder/jsjf/ArrayStack.javapackage jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
// -------------------------------------------------------
// Author: Yifu Wu
// Date: 03/10/16
// Source Name: ArrayStack<T>
// Due date: 03/10/16
// Description:
/**
* An array implementation of a stack in which the bottom of the
* stack is fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
publicclassArrayStack<T>implementsStackADT<T>
{
privatefinalstaticint DEFAULT_CAPACITY =100;
privateint top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
publicArrayStack()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
* @param initialCapacity the initial size of the array
*/
publicArrayStack(int initialCapacity)
{
top =0;
stack =(T[])(newObject[initialCapacity]);
}
/**
* Adds the specified element to the top of this stack, expanding
* the capacity of the array if necessary.
* @param element generic element to be pushed onto stack
*/
publicvoid push(T element)
{
if(size()== stack.length)
expandCapacity();
stack[top]= element;
top++;
}
/**
* Creates a new array to store the contents of this stack with
* twice the capacity of the old one.
*/
privatevoid expandCapacity()
{
//stack = Arrays.copyOf(stack, stack.length * 2);
System.out.println("Expanding stack capacity\n");
T[] temp =(T[])(newObject[2*top]);
for(int i=0; i< top; i++)
temp[i]= stack[i];
stack = temp;
}
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element removed from top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T pop()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top]=null;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T peek()throwsEmptyCollectionException
{
if(isEmpty())
thrownewEmptyCollectionException("stack");
return stack[top-1];
}
/**
* Returns the number of elements in ...
Add functions push(int n, Deque &dq) and pop(Deque &dq).
Functions push(int n, Deque &dq) and pop(Deque &dq) should call functions of the Deque class to simulate a stack's push and pop functions.
The Deque class should not be touched . I will use the original unmodified Deque class when testing your code.
Demonstrate to convert a base 10 number to base 2. Ask the user to enter a base 10 number, output the equivalent base 2 number. The main() function would create a Deque object and pass it by reference when calling the new
push(int n, Deque &dq) and pop(Deque &dq) functions simulating stack operations.
keep it simple and to the instructions and code provided please! and thank you!
// C++ implementation of De-queue using circular
// array
#include<iostream>
using namespace std;
// Maximum size of array or Dequeue
#define MAX 100
// A structure to represent a Deque
class Deque
{
int arr[MAX];
int front;
int rear;
int size;
public :
Deque(int size)
{
front = -1;
rear = 0;
this->size = size;
}
// Operations on Deque:
void insertfront(int key);
void insertrear(int key);
void deletefront();
void deleterear();
bool isFull();
bool isEmpty();
int getFront();
int getRear();
};
// Checks whether Deque is full or not.
bool Deque::isFull()
{
return ((front == 0 && rear == size-1)||
front == rear+1);
}
// Checks whether Deque is empty or not.
bool Deque::isEmpty ()
{
return (front == -1);
}
// Inserts an element at front
void Deque::insertfront(int key)
{
// check whether Deque if full or not
if (isFull())
{
cout << "Overflow\n" << endl;
return;
}
// If queue is initially empty
if (front == -1)
{
front = 0;
rear = 0;
}
// front is at first position of queue
else if (front == 0)
front = size - 1 ;
else // decrement front end by '1'
front = front-1;
// insert current element into Deque
arr[front] = key ;
}
// function to inset element at rear end
// of Deque.
void Deque ::insertrear(int key)
{
if (isFull())
{
cout << " Overflow\n " << endl;
return;
}
// If queue is initially empty
if (front == -1)
{
front = 0;
rear = 0;
}
// rear is at last position of queue
else if (rear == size-1)
rear = 0;
// increment rear end by '1'
else
rear = rear+1;
// insert current element into Deque
arr[rear] = key ;
}
// Deletes element at front end of Deque
void Deque ::deletefront()
{
// check whether Deque is empty or not
if (isEmpty())
{
cout << "Queue Underflow\n" << endl;
return ;
}
// Deque has only one element
if (front == rear)
{
front = -1;
rear = -1;
}
else
// back to initial position
if (front == size -1)
front = 0;
else // increment front by '1' to remove current
// front value from Deque
front = front+1;
}
// Delete element at rear end of Deque
void Deque::deleterear()
{
if (isEmpty())
{
cout << " Underflow\n" << endl ;
return ;
}
// Deque has only one element
if (front == rear)
{
front = -1;
rear = -1;
}
else if (rear == 0)
rear = size-1;
else
rear = rear-1;
}
// Returns front element of Deque
int Deque::getFront()
{
// check whether Deque is empty or not
if (isEmp.
/**
* @author Derek Harter
* @cwid 123 45 678
* @class
* @ide Visual Studio Community 2017
* @date
* @assg C++ Stacks videos
*
* @description A Stack ADT with two concrete impelementation
* examples: an array based stack implementaiton (AStack), and
* a linked list based implementation (LStack).
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//-------------------------------------------------------------------------
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*/
virtual int size() const = 0;
/** tostring
* Represent stack as a string
*/
virtual string tostring() const = 0;
// operload operators, mostly to support boolean comparison between
// two stacks for testing
bool operator==(const Stack<T>& rhs) const;
virtual const T& operator[](int index) const = 0;
// overload output stream operator for all stacks using tostring()
template <typename U>
friend ostream& operator<<(ostream& out, const Stack<U>& aStack);
};
/** Stack equivalence
* Compare two given stacks to determine if they are equal or not.
* stacks are equal if they are both of the same size, and each corresponding
* item on each stack is equal at the same position on the stack.
* This function relies on overloaded operator[] to access items on stack
* by index for the comparis.
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
Consider a double-linked linked list implementation with the followin.pdfsales98
Consider a double-linked linked list implementation with the following node: struct Node {int
data; Node *prev; Node *next;} Write a copyList method that is not a member of any class.
The method should take a head pointer and return another pointer. Do not modify the input.
Solution
struct Node {
Node *prev; // previous node
Node *next; // next node
int data; // stored value
};
#include
#include \"List.h\" // std: #include
using namespace std;
typedef DataList ; // std: typedef list Data;
int main() {
Data k;
// back stuff
k.push_back(5);
k.push_back(6);
cout << k.back() << endl;
k.pop_back();
// front stuff
k.push_front(4);
k.push_front(3);
cout << k.front() << endl;
k.pop_front();
// forward iterator
Data::iterator pos;
for (pos = k.begin(); pos != k.end(); ++pos)
cout << *pos << endl;
// output and delete list
while (!k.empty()) {
cout << k.front() << endl;
k.pop_front();
}
k.push_front(5);
k.push_front(6);
// remove and erase
k.remove(5);
pos = k.begin();
k.erase(pos);
k.push_front(5);
k.push_front(6);
// copy constructor
Data l = k;
// assignment operator
Data m;
m = k;
return 0;
}
// List.h
struct Node;
classIterator List;
class List {
public:
typedef ListIterator iterator;
// constructor
List();
// destructor
virtual ~List();
// copy constructor
List(const List& k);
// assignment operator
List& operator=(const List& k);
// insert value in front of list
void push_front(double data);
// insert value in back of list
void push_back(double data);
// delete value from front of list
void pop_front();
// delete value from back of list
void pop_back();
// return value on front of list
double front() const;
// return value on back of list
double back() const;
// delete value specified by iterator
void erase(const iterator& i);
// delete all nodes with specified value
void remove(double data);
// return true if list is empty
bool empty() const;
// return reference to first element in list
iterator begin() const;
// return reference to one past last element in list
iterator end() const;
private:
Node *head; // head of list
};
class ListIterator {
public:
// default constructor
ListIterator() {
i = 0;
}
// construct iterator for given pointer (used for begin/end)
ListIterator(Node *p) {
i = p;
}
// convert iterator to Node*
operator Node*() const {
return i;
}
// test two iterators for not equal
bool operator!=(const ListIterator& k) const {
return i != k.i;
}
// preincrement operator
ListIterator& operator++() {
i = i->next;
return *this;
}
// return value associated with iterator
double& operator*() const {
return i->data;
}
private:
Node *i; // current value of iterator
};
list.cpp
// delete list
static void deleteList(Node *head) {
Node *p = head->next;
while (p != head) {
Node *next = p->next;
delete p;
p = next;
}
delete head;
}
// copy list
static void copyList(const Node *from, Node *&to) {
// create dummy header
to = new Node;
to->next = to->prev = to;
// copy nodes
for (Node *p = from->next; p != from; p = p->next) {
Node *t = new Node;
t.
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfrajkumarm401
Complete the provided partial C++ Linked List program. Main.cpp is given and Link list header
file is also given. The given testfile listmain.cpp is given for demonstration of unsorted list
functionality. The functions header file is also given. Complete the functions of the header file
linked_list.h below.
=========================================================
// listmain.cpp
#include \"Linked_List.h\"
int main(int argc, char **argv)
{
float f;
Linked_List *theList;
cout << \"Simple List Demonstration\ \";
cout << \"(List implemented as an Array - Do not try this at home)\ \ \";
cout << \"Create a list and add a few tasks to the list\";
theList = new Linked_List(); // Instantiate a list object
theList->Insert(5, 3.1f); // Note: The argument to the funtion should be a float
theList->Insert(1, 5.6f); // A constant real number like 3.1 is interpreted as
theList->Insert(3, 8.3f); // a double unless it is explicitly defined as a float
theList->Insert(2, 7.4f); // by adding an \'f\' to the end of the number.
theList->Insert(4, 2.5f);
// Show what is in the list
theList->PrintList();
// Test the list length function
cout << \"\ List now contains \" << theList->ListLength() << \"items.\ \ \";
// Test delete function
cout << \"Testing delete of last item in list.\ \";
theList->Delete(4);
theList->PrintList();
// Test delete function
cout << \"Testing delete of first item in list.\ \";
theList->Delete(5);
theList->PrintList();
// Test delete function
cout << \"Testing delete of a middle item in list.\ \";
theList->Delete(3);
theList->PrintList();
// Test delete function with a known failure argument
cout << \"Testing failure in delete function.\ \";
if(theList->Delete(4))
cout << \"Oops! Should not have been able to delete.\ \";
else
cout << \"Unable to locate item to delete.\ \";
// Test search (known failure)
cout << \"Testing Search function. Search for key 3\ \";
if(theList->Search(3, &f))
cout << \"Search result: theData = %f\ \", f;
else
cout << \"Search result: Unable to locate item in list\ \";
// Test search (known success)
cout << \"Testing Search function. Search for key 2\ \";
if(theList->Search(2, &f))
cout << \"Search result: theData = \" << f << \"\ \";
else
cout << \"Search result: Unable to locate item in list\ \";
cout << \"\ \ End list demonstration...\";
return 0;
}
=====================================================================
===================
// linked_list.h functions
#include
using namespace std;
// Define a structure to use as the list item
struct ListItem
{
int key;
float theData;
ListItem *next;
};
class Linked_List
{
private:
ListItem *head; // Pointer to head of the list
public:
Linked_List(); // Class constructor
~Linked_List(); // Class destuctor
void ClearList(); // Remove all items from the list
bool Insert(int key, float f);// Add an item to the list
bool Delete(int key); // Delete an item from the list
bool Search(int key, float *retVal); // Search for an item in the list
int ListLength(); // Return numb.
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
PROBLEM STATEMENT:
In this assignment, you will complete DoubleEndedList.java that implements the ListInterface as
well as an interface called DoubleEndedInterface which represents the list's entries by using a
chain of nodes that has both a head reference and a tail reference. Be sure to read through the
code and understand the implementation.
WHAT IS PROVIDED:
- A driver class to test your code. You should not modify this file!
- A list interface (ListInterface.java)
- A double ended interface (DoubleEndedInterface.java)
- An incomplete DoubleEndedList class (DoubleEndedList.java)
WHAT YOU NEED TO DO:
4. Complete the DoubleEndedList class
4. Run the driver and make sure your output is exactly the same as mine (at the bottom of
Driver.java)
\} // end else numberofEntries--; else throw new IndexOut0fBoundsException("Illegal position
given to remove operation."); return result; // Return removed entry }//endreturnreve public T
replace(int givenPosition, T newEntry) \{ T replace(int givenPosition, T newEntry) \{ if
((givenPosition >=1)&& (givenPosition <= numberOfEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt (givenPosition); ToriginalEntry = desiredNode.getData();
desiredNode.setData(newEntry); return originalEntry; f // end if else throw new
IndexOut0fBoundsException("Illegal position given to replace operation."); replace if ((
givenPosition >=1)&& (givenPosition <= number0fEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt ( givenPosition); T originalEntry = desiredNode.
getData( ); desiredNode.setData(newEntry); return originalentry; \} // end if throw new
Index0ut0fBoundsException("Illegal position given to replace operation."); \} // end replace
public T getEntry(int givenPosition) \{ if ((givenPosition >=1) \&\& (givenPosition < =
number0fEntries ) ) \{ // Assertion: The list is not empty return getNodeAt (givenPosition).
getData(); else // end if throw new IndexOut0fBoundsException("Illegal position given to
getEntry operation."); \} // end getEntry public boolean contains ( T anEntry) \{ boolean found =
false; Node currentNode = firstNode; while (!found && (currentNode != null)) \{ if
(anEntry.equals (currentNode.getData())) else found = true; \} // end while currentNode =
currentNode. getNextNode () ; return found; \} // end contains public int getLength() \{ return
numberofEntries; \} // end getLength public boolean isEmpty() \{ return number0fEntries ==0;
\} // end isEmpty public T[] toArray() \{ // The cast is safe because the new array contains null
entries aSuppressWarnings ("unchecked") T[] result =(T[]) new 0bject [numberofEntries]; //
Unchecked cast int index =0; Node currentNode = firstNode; while ((index < numberOfEntries)
\&\& (currentNode != null)) \& result [ index ]= currentNode. getData () ; currentNode =
currentNode.getNextNode ( ); index++; 3 // end while return result; 3 // end toArray // Returns a
reference to the node at a given position. // Precondition: L.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
2. 2 struct Node{
double data;
Node* next;
};
class List {
public:
List(); // constructor
List(const List& list); // copy constructor
~List(); // destructor
List& operator=(const List& list); // assignment operator
bool empty() const; // boolean function
void addHead(double x); // add to the head
double deleteHead(); // delete the head and get the head element
// List& rest(); // get the rest of the list with the head removed
// double headElement() const; // get the head element
void addEnd(double x); // add to the end
double deleteEnd(); // delete the end and get the end element
// double endElement(); // get the element at the end
bool searchNode(double x); // search for a given x
void insertNode(double x); // insert x in a sorted list
void deleteNode(double x); // delete x in a sorted list
…
void print() const; // output
int length() const; // count the number of elements
private:
Node* head;
};
More complete list ADT
4. 4
Stack
A stack is a list in which insertion and deletion take
place at the same end
This end is called top
The other end is called bottom
Stacks are known as LIFO (Last In, First Out) lists.
The last element inserted will be the first to be retrieved
5. 5
Push and Pop
Primary operations: Push and Pop
Push
Add an element to the top of the stack
Pop
Remove the element at the top of the stack
top
empty stack
A
top
push an element
top
push another
A
B
top
pop
A
6. 6
Implementation of Stacks
Any list implementation could be used to
implement a stack
Arrays (static: the size of stack is given initially)
Linked lists (dynamic: never become full)
We will explore implementations based on
array and linked list
7. 7
class Stack {
public:
Stack(); // constructor
Stack(const Stack& stack); // copy constructor
~Stack(); // destructor
bool empty() const;
void push(const double x);
double pop(); // change the stack
double top() const; // keep the stack unchanged
// bool full(); // optional
// void print() const;
private:
…
};
Stack ADT
update,
‘logical’ constructor/destructor,
composition/decomposition
‘physical’
constructor/destructor
Compare with List, see that it’s ‘operations’ that define the type!
inspection,
access
8. 8
Using Stack
int main(void) {
Stack stack;
stack.push(5.0);
stack.push(6.5);
stack.push(-3.0);
stack.push(-8.0);
stack.print();
cout << "Top: " << stack.top() << endl;
stack.pop();
cout << "Top: " << stack.top() << endl;
while (!stack.empty()) stack.pop();
stack.print();
return 0;
}
result
10. 10
void List::addHead(int newdata){
Nodeptr newPtr = new Node;
newPtr->data = newdata;
newPtr->next = head;
head = newPtr;
}
void Stack::push(double x){
Node* newPtr = new Node;
newPtr->data = x;
newPtr->next = top;
top = newPtr;
}
From ‘addHead’ to ‘push’
Push (addHead), Pop (deleteHead)
11. 11
Implementation based on ‘existing’
linked lists
Optional to learn
Good to see that we may ‘re-use’ linked lists
12. 12
Now let’s implement a stack based on a linked list
To make the best out of the code of List, we implement Stack
by inheriting List
To let Stack access private member head, we make Stack
as a friend of List
class List {
public:
List() { head = NULL; } // constructor
~List(); // destructor
bool empty() { return head == NULL; }
Node* insertNode(int index, double x);
int deleteNode(double x);
int searchNode(double x);
void printList(void);
private:
Node* head;
friend class Stack;
};
13. 13
class Stack : public List {
public:
Stack() {}
~Stack() {}
double top() {
if (head == NULL) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else
return head->data;
}
void push(const double x) { InsertNode(0, x); }
double pop() {
if (head == NULL) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else {
double val = head->data;
DeleteNode(val);
return val;
}
}
void printStack() { printList(); }
};
Note: the stack
implementation
based on a linked
list will never be full.
from List
14. 14
Stack using arrays
class Stack {
public:
Stack(int size = 10); // constructor
~Stack() { delete [] values; } // destructor
bool empty() { return top == -1; }
void push(const double x);
double pop();
bool full() { return top == maxTop; }
double top();
void print();
private:
int maxTop; // max stack size = size - 1
int top; // current top of stack
double* values; // element array
};
15. 15
Attributes of Stack
maxTop: the max size of stack
top: the index of the top element of stack
values: point to an array which stores elements of stack
Operations of Stack
empty: return true if stack is empty, return false otherwise
full: return true if stack is full, return false otherwise
top: return the element at the top of stack
push: add an element to the top of stack
pop: delete the element at the top of stack
print: print all the data in the stack
16. 16
Allocate a stack array of size. By default,
size = 10.
Initially top is set to -1. It means the stack is empty.
When the stack is full, top will have its maximum value, i.e.
size – 1.
Stack::Stack(int size /*= 10*/) {
values = new double[size];
top = -1;
maxTop = size - 1;
}
Although the constructor dynamically allocates the stack array,
the stack is still static. The size is fixed after the initialization.
Stack constructor
17. 17
void push(const double x);
Push an element onto the stack
Note top always represents the index of the top
element. After pushing an element, increment top.
void Stack::push(const double x) {
if (full()) // if stack is full, print error
cout << "Error: the stack is full." << endl;
else
values[++top] = x;
}
18. 18
double pop()
Pop and return the element at the top of the stack
Don’t forgot to decrement top
double Stack::pop() {
if (empty()) { //if stack is empty, print error
cout << "Error: the stack is empty." << endl;
return -1;
}
else {
return values[top--];
}
}
19. 19
double top()
Return the top element of the stack
Unlike pop, this function does not remove the top
element
double Stack::top() {
if (empty()) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else
return values[top];
}
20. 20
void print()
Print all the elements
void Stack::print() {
cout << "top -->";
for (int i = top; i >= 0; i--)
cout << "t|t" << values[i] << "t|" << endl;
cout << "t|---------------|" << endl;
}
21. 21
Stack Application:
Balancing Symbols
To check that every right brace, bracket, and
parentheses must correspond to its left counterpart
e.g. [( )] is legal, but [( ] ) is illegal
Algorithm
(1) Make an empty stack.
(2) Read characters until end of file
i. If the character is an opening symbol, push it onto the stack
ii. If it is a closing symbol, then if the stack is empty, report an error
iii. Otherwise, pop the stack. If the symbol popped is not the
corresponding opening symbol, then report an error
(3) At end of file, if the stack is not empty, report an error
22. 22
Stack Application: function calls and
recursion
Take the example of factorial! And run it.
#include <iostream>
using namespace std;
int fac(int n){
int product;
if(n <= 1) product = 1;
else product = n * fac(n-1);
return product;
}
void main(){
int number;
cout << "Enter a positive integer : " << endl;;
cin >> number;
cout << fac(number) << endl;
}
23. 23
Assume the number typed is 3.
fac(3): has the final returned value 6
3<=1 ? No.
product3 = 3*fac(2) product3=3*2=6, return 6,
fac(2):
2<=1 ? No.
product2 = 2*fac(1) product2=2*1=2, return 2,
fac(1):
1<=1 ? Yes.
return 1
Tracing the program …
25. 25
Array versus
linked list implementations
push, pop, top are all constant-time
operations in both array and linked list
implementation
For array implementation, the operations are
performed in very fast constant time
27. 27
Queue
A queue is also a list. However, insertion is
done at one end, while deletion is performed
at the other end.
It is “First In, First Out (FIFO)” order.
Like customers standing in a check-out line in a
store, the first customer in is the first customer
served.
28. 28
Enqueue and Dequeue
Primary queue operations: Enqueue and Dequeue
Like check-out lines in a store, a queue has a front
and a rear.
Enqueue – insert an element at the rear of the
queue
Dequeue – remove an element from the front of
the queue
Insert
(Enqueue)
Remove
(Dequeue) rearfront
29. 29
Implementation of Queue
Just as stacks can be implemented as arrays
or linked lists, so with queues.
Dynamic queues have the same advantages
over static queues as dynamic stacks have
over static stacks
35. 35
Dequeue (deleteHead)
double Queue::dequeue() {
double x;
if (empty()) {
cout << "Error: the queue is empty." << endl;
exit(1); // return false;
}
else {
x = front->data;
Node* nextNode = front->next;
delete front;
front = nextNode;
counter--;
}
return x;
}
front
583
8 5
front
36. 36
Printing all the elements
void Queue::print() {
cout << "front -->";
Node* currNode = front;
for (int i = 0; i < counter; i++) {
if (i == 0) cout << "t";
else cout << "tt";
cout << currNode->data;
if (i != counter - 1)
cout << endl;
else
cout << "t<-- rear" << endl;
currNode = currNode->next;
}
}
37. 37
Queue using Arrays
There are several different algorithms to
implement Enqueue and Dequeue
Naïve way
When enqueuing, the front index is always fixed
and the rear index moves forward in the array.
front
rear
Enqueue(3)
3
front
rear
Enqueue(6)
3 6
front
rear
Enqueue(9)
3 6 9
38. 38
Naïve way (cont’d)
When dequeuing, the front index is fixed, and the
element at the front the queue is removed. Move
all the elements after it by one position.
(Inefficient!!!)
Dequeue()
front
rear
6 9
Dequeue() Dequeue()
front
rear
9
rear = -1
front
39. 39
A better way
When enqueued, the rear index moves forward.
When dequeued, the front index also moves forward
by one element
XXXXOOOOO (rear)
OXXXXOOOO (after 1 dequeue, and 1 enqueue)
OOXXXXXOO (after another dequeue, and 2 enqueues)
OOOOXXXXX (after 2 more dequeues, and 2 enqueues)
(front)
The problem here is that the rear index cannot move beyond the
last element in the array.
40. 40
Using Circular Arrays
Using a circular array
When an element moves past the end of a circular
array, it wraps around to the beginning, e.g.
OOOOO7963 4OOOO7963 (after Enqueue(4))
How to detect an empty or full queue, using a
circular array algorithm?
Use a counter of the number of elements in the queue.
41. 41
class Queue {
public:
Queue(int size = 10); // constructor
Queue(Queue& queue); // not necessary!
~Queue() { delete [] values; } // destructor
bool empty(void);
void enqueue(double x); // or bool enqueue();
double dequeue();
bool full();
void print(void);
private:
int front; // front index
int rear; // rear index
int counter; // number of elements
int maxSize; // size of array queue
double* values; // element array
};
full() is not essential, can be embedded
42. 42
Attributes of Queue
front/rear: front/rear index
counter: number of elements in the queue
maxSize: capacity of the queue
values: point to an array which stores elements of the queue
Operations of Queue
empty: return true if queue is empty, return false otherwise
full: return true if queue is full, return false otherwise
enqueue: add an element to the rear of queue
dequeue: delete the element at the front of queue
print: print all the data
43. 43
Queue constructor
Queue(int size = 10)
Allocate a queue array of size. By default, size = 10.
front is set to 0, pointing to the first element of the
array
rear is set to -1. The queue is empty initially.
Queue::Queue(int size /* = 10 */) {
values = new double[size];
maxSize = size;
front = 0;
rear = -1;
counter = 0;
}
44. 44
Empty & Full
Since we keep track of the number of elements
that are actually in the queue: counter, it is
easy to check if the queue is empty or full.
bool Queue::empty() {
if (counter==0) return true;
else return false;
}
bool Queue::full() {
if (counter < maxSize) return false;
else return true;
}
45. 45
Enqueue
void Queue::enqueue(double x) {
if (full()) {
cout << "Error: the queue is full." << endl;
exit(1); // return false;
}
else {
// calculate the new rear position (circular)
rear = (rear + 1) % maxSize;
// insert new item
values[rear] = x;
// update counter
counter++;
// return true;
}
}
Or ‘bool’ if you want
46. 46
Dequeue
double Queue::dequeue() {
double x;
if (empty()) {
cout << "Error: the queue is empty." << endl;
exit(1); // return false;
}
else {
// retrieve the front item
x = values[front];
// move front
front = (front + 1) % maxSize;
// update counter
counter--;
// return true;
}
return x;
}
47. 47
Printing the elements
void Queue::print() {
cout << "front -->";
for (int i = 0; i < counter; i++) {
if (i == 0) cout << "t";
else cout << "tt";
cout << values[(front + i) % maxSize];
if (i != counter - 1)
cout << endl;
else
cout << "t<-- rear" << endl;
}
}
48. 48
Using Queueint main(void) {
Queue queue;
cout << "Enqueue 5 items." << endl;
for (int x = 0; x < 5; x++)
queue.enqueue(x);
cout << "Now attempting to enqueue again..." << endl;
queue.enqueue(5);
queue.print();
double value;
value=queue.dequeue();
cout << "Retrieved element = " << value << endl;
queue.print();
queue.enqueue(7);
queue.print();
return 0;
}