Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write the definition for the following functions in c++ format #ifndef HW4_TODO_

ID: 3593596 • Letter: W

Question

write the definition for the following functions in c++ format

#ifndef HW4_TODO_STACKLINKEDLIST

#define HW4_TODO_STACKLINKEDLIST

#include <string>

struct TodoItem

{

std::string todo;

TodoItem *next;

};

class TodoStackLinkedList

{  

public:

TodoStackLinkedList();

~TodoStackLinkedList();

bool isEmpty();

void push(std::string todoItem);

void pop();

TodoItem* peek();

TodoItem* getStackHead() { return stackHead; }

private:

TodoItem* stackHead; // pointer to the TodoItem that will be popped next

};

#endif

Explanation / Answer

Following is the C++ program:

#include<iostream>

using namespace std;

struct TodoItem

{

string todo;

TodoItem *next;

};

class TodoStackArray

{

public:

TodoStackArray();

~TodoStackArray();

bool isEmpty();

void push(std::string todoItem);

void pop();

TodoItem* peek();

TodoItem* getStackHead();

private:

TodoItem* stackHead;

};

TodoStackArray::TodoStackArray() {

//Initialize stackHead to NULL

stackHead=NULL;

}

TodoStackArray::~TodoStackArray() {

//Deallocate memory of all elements of stack

TodoItem *t;

while(stackHead) {

t=stackHead;

stackHead=stackHead->next;

delete t;

}

}

bool TodoStackArray::isEmpty() {

if (stackHead == NULL)

return true;

return false;

}

TodoItem* TodoStackArray::getStackHead() {

return stackHead;

}

TodoItem* TodoStackArray::peek() {

return stackHead;

}

void TodoStackArray::push(string todoItem) {

//Allocate memory to a new TodoItem element & add it to head of stack.

struct TodoItem *t = new TodoItem;

t->todo=todoItem;

t->next=NULL;

if (stackHead == NULL)

stackHead=t;

else {

t->next = stackHead;

stackHead=t;

}

}

void TodoStackArray::pop() {

if (!isEmpty()) {

// Deallocate the memory of the object being deleted

TodoItem *t=stackHead;

stackHead=stackHead->next;

delete t;

}

else

cout << "Stack empty, cannot pop an item." << endl;

}

int main()

{

TodoStackArray stack;

stack.push("Hello");

cout<< (stack.peek())->todo<< endl;

stack.push("This");

cout<< stack.peek()->todo<<endl;

stack.push("IS");

cout<< stack.peek()->todo<<endl;

stack.push("My");

cout<< stack.peek()->todo<<endl;

stack.push("List");

cout<< stack.peek()->todo<<endl;

stack.push("Stack"); //Overflow condition

stack.pop();

cout<< stack.peek()->todo<<endl;

stack.pop();

cout<< stack.peek()->todo<<endl;

stack.pop();

cout<< stack.peek()->todo<<endl;

stack.pop();

cout<< stack.peek()->todo<<endl;

stack.pop();

stack.pop();

stack.pop();

return 0;

}

Output:

Hello
This
IS
My
List
List
My
IS
This
Stack empty, cannot pop an item.