Trending February 2024 # Stack In C++ Stl With Example # Suggested March 2024 # Top 5 Popular

You are reading the article Stack In C++ Stl With Example updated in February 2024 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Stack In C++ Stl With Example

What is std::stack?

A stack is a data structure that operates based on LIFO (Last In First Out) technique. The std::stack allows elements to be added and removed from one end only.

The std::stack class is a container adapter. Container objects hold data of a similar data type. You can create a stack from various sequence containers. If no container is provided, the deque containe will be used by default. Container adapters don’t support iterators, so it can’t be used to manipulate data.

In this C++ tutorial, you will learn

Stack Syntax

Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type.

Container – is the Type of underlying container object.

Member Types

Here are stack member types:

value_type- The first template parameter, T. It denotes the element types.

container_type- The second template parameter, Container. It denotes the underlying container type.

size_type- Unsigned integral type.

Operations in Stack

A C++ stack supports the following basic operations:

push – It adds/pushes an item into the stack.

pop – It removes/pops an item from the stack.

peek – Returns the top item of the stack without removing it.

isFull – Checks whether a stack is full.

isEmpty – Checks whether a stack is empty.

Stack Implementation

Step 1) We initially have an empty stack. The top of an empty stack is set to -1.

Step 2) Next, we have pushed the element 5 into the stack. The top of the stack will points to the element 5.

Step 3) Next, we have pushed the element 50 into the stack. The top of the stack shifts and points to the element 50.

Step 4) We have then performed a pop operation, removing the top element from the stack. The element 50 is popped from the stack. The top of the stack now points to the element 5.

push() and pop()

The stack::push() functions adds new item to the top of stack. The stack size is increased by a 1 after the insertion. The function takes this syntax:

stack.push(value)

The value is the item to insert into the stack.

The stack:: pop() function removes the top element of the stack. This is the newest item of the stack. The stack size is reduced by 1 after the removal. Here is the function syntax:

stack.pop()

The function takes no parameters.

Example 1:

using namespace std; int main() { st.push(10); st.push(20); st.push(30); st.push(40);

st.pop(); st.pop();

while (!st.empty()) { cout << ‘ ‘ << st.top(); st.pop(); } }

Output:

Here is a screenshot of the code:

Code Explanation:

Include the iostream header file in our code to use its functions.

Include the stack header file in our code to use its functions.

Include the std namespace in our code to use its classes without calling it.

Call the main() function. The program logic should be added within this function.

Create a stack st to store integer values.

Use the push() function to insert the value 10 into the stack.

Use the push() function to insert the value 20 into the stack.

Use the push() function to insert the value 30 into the stack.

Use the push() function to insert the value 40 into the stack.

Use the pop() function to remove the top element from the stack, that is, 40. The top element now becomes 30.

Use the pop() function to remove the top element from the stack, that is, 30. The top element now becomes 20.

Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.

Printing the current contents of the stack on the console.

Call the pop() function on the stack.

End of the body of the while loop.

End of the main() function body.

Stacks have inbuilt functions that you can use to play around with the stack and its values. These include:

empty()- checks whether a stack is empty or not.

size()- returns the size of stack, that is, number of elements in a stack.

top()- accesses stack element at the top.

Example 2:

using namespace std; { while (!ms.empty()) { cout << ‘t’ << ms.top(); ms.pop(); } cout << ‘n’; } int main() { st.push(32); st.push(21); st.push(39); st.push(89); st.push(25);

cout << “The stack st is: “; createStack(st); cout << “n st.size() : ” << st.size(); cout << “n st.top() : ” << st.top(); cout << “n st.pop() : “; st.pop(); createStack(st); return 0; }

Output:

Here is a screenshot of the code:

Code Explanation:

Include the iostream header file in our code in order to use its functions.

Include the stack header file in our code in order to use its functions.

Include the std namespace in our program in order to use its classes without calling it.

Create the function createStack that we can use to create the stack mystack. The stack will hold a set of integers.

The beginning of the body of the createStack function.

Create an instance of the mystack datatype and giving it the name ms.

Use the while loop and the empty() function to check whether the stack is empty.

The start of the body of the while loop.

Use the top() function stored at the top of the stack. The t character will create a new tab.

Use the pop() function to delete the element at the top of the stack.

End of the body of the while loop.

Print a blank line on the console.

End of the body of the createStack function.

Call the main() function. The program logic should be added within the body of the main() function.

The start of the body of function main().

Create a stack object st.

Use the push() function to insert the element 32 into the stack.

Use the push() function to insert the element 21 into the stack.

Use the push() function to insert the element 39 into the stack.

Use the push() function to insert the element 89 into the stack.

Use the push() function to insert the element 25 into the stack.

Print some text on the console.

Call the createStack function to execute the above insert operations into the stack.

Print the size of the stack on the console alongside other text.

Print the element at the top of the stack on the console.

Print some text on the console.

Delete the element at the top of the stack. It will then return the elements remaining in the stack.

Call the createStack function to execute the above operations.

The program must return value upon successful completion.

End of the body of function main().

emplace() and swap()

These are other inbuilt stack functions:

emplace()- constructs then inserts new element to top of stack.

swap()- exchanges stack contents with another stack’s contents.

Example 3:

using namespace std; int main() {

st1.emplace(12); st1.emplace(19);

st2.emplace(20); st2.emplace(23);

st1.swap(st2);

cout << “st1 = “; while (!st1.empty()) { cout << st1.top() << ” “; st1.pop(); }

cout << endl << “st2 = “; while (!st2.empty()) { cout << st2.top() << ” “; st2.pop(); } }

Output:

Here is a screenshot of the code:

Code Explanation:

Include the iostream header file in our code to use its functions.

Include the stack header file in our code to use its functions.

Include the cstdlib header file in our code to use its functions.

Include the std namespace in our code to use its classes without calling it.

Call the main() function. The program logic will be added within the body of this function.

Declare a stack named st1 to store integer values.

Declare a stack named st2 to store integer values.

Use the emplace() function to insert the integer 12 into the stack named st1.

Use the emplace() function to insert the integer 19 into the stack named st1.

Use the emplace() function to insert the integer 20 into the stack named st2.

Use the emplace() function to insert the integer 23 into the stack named st2.

Use the swap() function to swap the contents of the two stacks, st1 and st2. The contents of the stack st1 should be moved to the stack st2. The contents of the stack st2 should be moved to the stack st1.

Print some text on the console.

Use the while statement and the empty() function to check whether the stack st1 is not empty.

Print the contents of the stack st1 on the console. The ” ” adds space between the stack elements when printing them on the console.

Execute the pop() function on the stack st1 to remove the top element.

End of the body of the while statement.

Print some text on the console. The endl is a C++ keyword for end line. It moves the mouse cursor to the next line to begin printing from there.

Use the while statement and the empty() function to check whether the stack st2 is not empty.

Print the contents of the stack st2 on the console. The ” ” adds space between the stack elements when printing them on the console.

Execute the pop() function on the stack st2 to remove the top element.

End of the body of the while statement.

End of the body of the main() function.

Stack in STL

The STL (Standard Template Library) comes with template classes that provide common C++ data structures. Therefore, a stack can also be implemented in STL. We simply include this library in our code and use it to define a stack.

The above syntax declares a stack st to elements of data type T.

Example 3:

using namespace std; int main() { st.push(12); st.push(19); st.push(20); cout << st.top(); cout << st.size(); }

Output:

Here is a screenshot of the code:

Code Explanation:

Include the iostream header file in our code to use its functions.

Include the stack header file in our code to use its functions.

Include the cstdlib header file in our code to use its functions.

Include the std namespace in our code to use its classes without calling it.

Call the main() function. The program logic should be added within the body of this function.

Declare a stack st to store integer data.

Add the element 12 to the stack.

Add the element 19 to the stack.

Add the element 20 to the stack.

Print the element at the top of the stack on the console.

Print the size of the stack on the console.

End of the body of the function main().

Summary:

A stack is a data structure that operates based on the LIFO (Last In first Out) technique.

The std::stack only allows items to be added and removed from one end.

The std::stack class is a container adapter, holding items of a similar data type.

A stack can be created from various sequence containers.

If you don’t provide a container, the deque container will be used by default.

The push() function is for inserting items into the stack.

The pop() function is for removing the top item from the step.

The empty() function is for checking whether a stack is empty or not.

You're reading Stack In C++ Stl With Example

Encapsulation In Java Oops With Example

What is Encapsulation in Java?

Encapsulation in Java is a mechanism to wrap up variables(data) and methods(code) together as a single unit. It is the process of hiding information details and protecting data and behavior of the object. It is one of the four important OOP concepts. The encapsulate class is easy to test, so it is also better for unit testing.

In this tutorial, you will learn-

Learn Encapsulation with an Example

To understand what is encapsulation in detail consider the following bank account class with deposit and show balance methods

class Account { private int account_number; private int account_balance; public void show Data() { } public void deposit(int a) { if (a < 0) { } else account_balance = account_balance + a; } }

Suppose a hacker managed to gain access to the code of your bank account. Now, he tries to deposit amount -100 into your account by two ways. Let see his first method or approach.

Approach 1: He tries to deposit an invalid amount (say -100) into your bank account by manipulating the code.

Now, the question is – Is that possible? Let investigate.

Usually, a variable in a class are set as “private” as shown below. It can only be accessed with the methods defined in the class. No other class or object can access them.

If a data member is private, it means it can only be accessed within the same class. No outside class can access private data member or variable of other class.

So in our case hacker cannot deposit amount -100 to your account.

Approach 2: Hacker’s first approach failed to deposit the amount. Next, he tries to do deposit a amount -100 by using “deposit” method.

But method implementation has a check for negative values. So the second approach also fails.

Thus, you never expose your data to an external party. Which makes your application secure.

The entire code can be thought of a capsule, and you can only communicate through the messages. Hence the name encapsulation.

Data Hiding in Java

Data Hiding in Java is hiding the variables of a class from other classes. It can only be accessed through the method of their current class. It hides the implementation details from the users. But more than data hiding, it is meant for better management or grouping of related data.

To achieve a lesser degree of encapsulation in Java, you can use modifiers like “protected” or “public”. With encapsulation, developers can change one part of the code easily without affecting other.

Getter and Setter in Java

Getter and Setter in Java are two conventional methods used to retrieve and update values of a variable. They are mainly used to create, modify, delete and view the variable values. The setter method is used for updating values and the getter method is used for reading or retrieving the values. They are also known as an accessor and mutator.

The following code is an example of getter and setter methods:

class Account{ private int account_number; private int account_balance; public int getBalance() { return this.account_balance; } public void setNumber(int num) { this.account_number = num; } }

Abstraction vs. Encapsulation

Often encapsulation is misunderstood with Abstraction. Lets study-

Encapsulation is more about “How” to achieve a functionality

Abstraction is more about “What” a class can do.

A simple example to understand this difference is a mobile phone. Where the complex logic in the circuit board is encapsulated in a touch screen, and the interface is provided to abstract it out.

Advantages of Encapsulation in Java

Encapsulation is binding the data with its related functionalities. Here functionalities mean “methods” and data means “variables”

So we keep variable and methods in one place. That place is “class.” Class is the base for encapsulation.

With Java Encapsulation, you can hide (restrict access) to critical data members in your code, which improves security

As we discussed earlier, if a data member is declared “private”, then it can only be accessed within the same class. No outside class can access data member (variable) of other class.

However, if you need to access these variables, you have to use public “getter” and “setter” methods.

Calculator (Example With Excel Template)

Cost-Benefit Analysis Formula (Table of Contents)

Start Your Free Investment Banking Course

Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others

What is the Cost-Benefit Analysis Formula?

The term “cost-benefit analysis” refers to the analytical technique that compares the benefits of a project with its associated costs. In other words, all the expected benefits out a project are placed on one side of the balance and the costs that have to be incurred are placed on the other side. The cost-benefit analysis can be executed either using “benefit-cost ratio” or “net present value”.

The formula for a benefit-cost ratio can be derived by dividing the aggregate of the present value of all the expected benefits by an aggregate of the present value of all the associated costs, which is represented as,

Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs

The formula for net present value can be derived by deducting the sum of the present value of all the associated costs from the sum of the present value of all the expected benefits, which is represented as,

Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs

Example of Cost-Benefit Analysis Formula (With Excel Template)

Let’s take an example to understand the calculation of Cost-Benefit Analysis in a better manner.

You can download this Cost-Benefit Analysis Excel Template here – Cost-Benefit Analysis Excel Template

Cost-Benefit Analysis Formula – Example #1

Let us take the example of a financial technology start-up which is contemplating on hiring two new programmers. The promoter expects the programmers to increase the revenue by 25% while incurring an additional cost of $45,000 in the next one year. The help promoter decides whether to go ahead with the recruitment based on cost-benefit analysis if the revenue of the company in the current year is $220,000 and the relevant discount rate is 5%.

Solution:

PV of Benefit is Calculated as:

PV of Benefit= $55,000 / (1 + 5%)

PV of Benefit = $52,380.95

PV of Cost is Calculated as:

PV of Cost = $35,000 / (1 + 5%)

PV of Cost = $33,333.33

Benefit-Cost Ratio is calculated using the formula given below

Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs

Benefit-Cost Ratio = $52,380.95 / $33,333.33

Benefit-Cost Ratio = 1.57x

Net Present Value is calculated using the formula given below

Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs

Net Present Value = $52,380.95 – $33,333.33

Net Present Value = $19,047.62

Therefore, both the method of cost-benefit analysis suggests that the promoter should go ahead with the recruitment.

Cost-Benefit Analysis Formula – Example #2

Let us take the example of two projects to illustrate the use of cost-benefit analysis. The sum of the present value of expected benefits from Project 1 is $50 million with the sum of the present value of associated costs of $30 million. On the other hand, the sum of the present value of expected benefits from Project 2 is $10 million with the sum of the present value of associated costs of $5 million. Discuss which project is better based on cost-benefit analysis.

Solution:

Benefit-Cost Ratio is calculated using the formula given below

Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs

For Project 1

Benefit-Cost Ratio = $50,000,000 / $30,000,000

Benefit-Cost Ratio = 1.67x

For Project 2

Benefit-Cost Ratio = $10,000,000 / $5,000,000

Benefit-Cost Ratio = 2.00x

Net Present Value is calculated using the formula given below

Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs

For Project 1

Net Present Value = $50,000,000 – $30,000,000

Net Present Value = $20,000,000

For Project 2

Net Present Value = $10,000,000 – $5,000,000

Net Present Value = $5,000,000

Explanation

The formula for cost-benefit analysis can be calculated by using the following steps:

Step 1: Firstly, Calculate all the cash inflow from the subject project, which is either revenue generation or savings due to operational efficiency.

Step 2: Next, Calculate all the cash outflow into the project, which are the costs incurred in order to maintain and keep the project up and running.

Step 3: Next, Calculate the discounting factor based on the current pricing of assets with a similar risk profile.

Step 4: Next, based on the discounting factor, calculate the present value of all the cash inflow and outflow. Then, add up the present value of all the cash inflow as ∑PV of all the expected benefits and outflow as ∑PV of all the associated costs.

Step 5: Now, the formula for a benefit-cost ratio can be derived by dividing aggregate of the present value of all the expected benefits (step 4) by aggregate of the present value of all the associated costs (step 4) as shown below.

Benefit-Cost Ratio = ∑PV of all the Expected Benefits / ∑PV of all the Associated Costs

Step 6: Now, the formula for net present value can be derived by deducting the sum of the present value of all the associated costs (step 4) from the sum of the present value of all the expected benefits (step 4) as shown below.

Net Present Value = ∑PV of all the Expected Benefits – ∑PV of all the Associated Costs

Relevance and Use of Cost-Benefit Analysis Formula

The importance of cost-benefit analysis lies in the fact that it is used for assessing the feasibility of an opportunity, comparing projects, appraising opportunity cost and building real-life scenario-based sensitivity testing. In this way, this technique helps in ascertaining the accuracy of an investment decision and provides a platform for its comparison with similar proposals.

Cost-Benefit Analysis Formula Calculator

You can use the following Cost-Benefit Analysis Formula Calculator

∑PV of all the Expected Benefits ∑PV of all the Associated Costs Benefit-Cost Ratio   Benefit-Cost Ratio = ∑PV of all the Expected Benefits =

∑PV of all the Associated Costs

0

= 0

0

Recommended Articles

This is a guide to Cost-Benefit Analysis Formula. Here we discuss how to calculate the Cost-Benefit Analysis Formula along with practical examples. We also provide a Cost-Benefit Analysis calculator with a downloadable excel template. You may also look at the following articles to learn more –

Junit Errorcollector @Rule With Example

In a normal scenario, whenever you identify any error during test execution, you would stop the test, fix the error and re-run the test.

But JUnit has a slightly different approach. With JUnit error collector, you can still continue with the test execution even after an issue is found or test fails. Error collector collects all error objects and reports it only once after the test execution is over.

In this tutorial, you will learn-

Why use Error Collector?

While writing a test script, you want to execute all the tests even if any line of code fails due to network failure, assertion failure, or any other reason. In that situation, you can still continue executing test script using a special feature provided by JUnit known as “error collector.”

For this, JUnit uses @Rule annotation which is used to create an object of error collector. Once the object for error collector is created, you can easily add all the errors into the object using method addError (Throwable error). As you know, that Throwable is the super class of Exception and Error class in Java. When you add errors in this way, these errors will be logged in JUnit test result .

The benefit of adding all errors in an Error Collector is that you can verify all the errors at once. Also, if the script fails in the middle, it can still continue executing it

Note: In the case of using simple assert or try/catch block , using error collector method won’t be possible.

Sample code

To understand more on Error Collector, see below code example which demonstrates how to create an Error Collector object and add all the errors in that object to track the issue :

package guru99.junit; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; public class ErrorCollectorExample { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("There is an error in first line")); collector.addError(new Throwable("There is an error in second line")); collector.checkThat(getResults(), not(containsString("here is an error"))); be logged in. } } What is @Rule in jUnit?

JUnit provides special kind of handling of tests, Test Case or test suite by using @rule annotation. Using @rule, you can easily add or redefine the behaviour of the test.

There are several built-in rules provided by JUnit API that a tester can use, or even you can write our own rule.

See below line of code, which shows how to use @rule annotation along with Error Collector:

@Rule public ErrorCollector collector= new ErrorCollector(); Example using ErrorCollector

To understand error collector, let’s create a class and a rule to collect all the errors. You will add all the errors using addError(throwable) here.

See below code which simply creates a rule which is nothing but creating “Error Collector object.” Which is further used to add all the errors in order to report the issue at the end:

ErrorCollectorExample.java

package guru99.junit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; public class ErrorCollectorExample { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("There is an error in first line")); collector.addError(new Throwable("There is an error in second line")); System.out.println("Hello"); try { Assert.assertTrue("A " == "B"); } catch (Throwable t) { collector.addError(t); } System.out.println("World!!!!"); } }

TestRunner.java

Let’s add above test class in a test runner and execute it to collect all errors. See below code:

package guru99.junit; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(ErrorCollectorExample.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println("Result=="+result.wasSuccessful()); } }

Output:

See the failure trace which traces all the errors in one place:

Benefits of JUnit ErrorCollector

You can use JUnit assertion for functional or GUI validation e.g.

assertEquals(String message, Object expected, Object actual) which compare that two objects are equals.

Similarly, assertTrue(Boolean condition) asserts that a condition is true.

Using assertion, validation test becomes easy. But one major issue is that test execution will stop even if a single assertion fails.

Test continuity and recovery handling is crucial to test automation success. Error Collector is the best way to handle such kind of scenarios.

Summary:

Junit error collector allows a test to continue even after the first issue is found and test fails at the end

Error collector collects all error objects and reports it only, after all, the test execution over

The benefit of adding all errors in an Error Collector is that you can verify all the errors at once

Error collector simply adds errors using method addError(throwable err) provided by ErrorCollector.java.

How Sizeof() Operator Work In C++ With Examples

Introduction to C++ sizeof()

The sizeof() is an operator in C and C++. It is an unary operator which assists a programmer in finding the size of the operand which is being used. The result of this operator is an integral type which is usually signified by size_t. This operator is usually used with data types which can be primitive data types like integer, float, pointer, etc. It can also give size of complex datatypes like structure, union, etc. It is a compile time operator which will tell the size of any data type and compute the size of operand.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below is the syntax of using sizeof():

sizeof(type) sizeof expression

The sizeof function in the first type, will give the output as an size in bytes of the object of the type which is sent. The second type is the size in bytes of the object which is in the type of expression. The size will be the size once the expression is evaluated. In both these versions the constant expression of the standard type that is size_t.

How sizeof() Operator work in C++?

The sizeof() operator can be used to find the size of datatype or expressions. They work in a very easy manner of taking these as arguments and work on them by returning the size in bytes.

Code:

using namespace std; int main() { cout << “Size of char : ” << sizeof(char) << endl; cout << “Size of int : ” << sizeof(int) << endl; cout << “Size of expression 5 + 8 is : ” << sizeof(5 + 8) << endl; return 0; }

As stated earlier the sizeof function will help us in getting the size of every datatype. Hence it uses these data types as an argument and return the data size of each data type. We have also taken size of expression where we are adding 2 integers. It will calculate these and the result will also be an integer. Hence the output for this will be also 4. The output of above function and code will be the number of bytes each variable uses. To check a few the output for char will be as below.

Output:

Examples of C++ sizeof()

Given below are the examples mentioned:

Example #1

Operand as a data type.

Code:

using namespace std; int main() { cout << “The size of char data type is ” << sizeof(char)<<“n”; cout << “The size of int data type is ” << sizeof(int)<<“n”; cout << “The size of float data type is “<< sizeof(float)<<“n”; cout << “The size of double data type is ” << sizeof(double)<<“n”; return 0; }

Output:

Example #2

Operand as an expression.

Code:

using namespace std; int main() { int a = 7; float d = 15.21; cout << “The addition of int and float is a float as follows: ” << a + d; cout << “nThe size of the expression is ” << sizeof(a + d); return 0; }

The above code with return the size of the data type of the resulting expression. Here we have declared two variables. One variable is an integer and the second variable is a float. We are now adding these two variables in the expression of which we will be finding the size of. The result of this expression will be a float. Hence the sizeof will be the size of float data type.

Output:

Example #3

Finding number of elements in the array.

Code:

using namespace std; int main() { int array1[] = { 1,5,76,89,23,06 }; cout << “The number of elements which are present in the array are : “ <<(sizeof(array1) / sizeof(array1[0])); return 0; }

In addition to giving the size of expressions and data types, the sizeof operator can also be used to find the number of elements in an array. Here we have defined an array ‘array1’. We have a few elements added to it. In order to get the count of these elements and get exactly how many elements are present in it we can simply make use of the sizeof operator.

We specify the array name and the first index that is array1[0] which helps us in starting he count from beginning. It will start from index 0 and count till the end. Once it reached the end it will display the number of elements. It will be returned by this sizeof() function that we have.

Output:

Conclusion

The sizeof() operator is a function which returns the size of any data type, expression, array, etc. It takes the data type or expression as a part of argument which is mandatory and returns the result which is size of that data type in bytes. If it is an array it will return the number of elements present in it. It is a very useful function when we have to allocate memory. We can calculate the size and allocate memory as per requirement and as a result save a lot of space which otherwise will be occupied.

Recommended Articles

This is a guide to C++ sizeof(). Here we discuss how sizeof() operator work in C++ along with examples respectively. You may also have a look at the following articles to learn more –

How To Implement Stack Method In Javascript?

Definition of JavaScript Stack

JavaScript stack can be implemented easily by using the array data structure available in it. A stack is a basic data structure that allows us to store the data and retrieve it in Last In First Out (LIFO) or First In Last Out (FILO) order. This means the data which is inserted first into the stack can be removed at last or the data which is inserted at the last can be removed first. The data access to the stack is only accessible from one end of it. JavaScript stack will have two main methods, one is to insert the element into the stack and the second is to remove the element from the stack.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Methods to Implement Javascript Stack 1. Push

This method will insert the element into the stack. The element will be inserted on the top of the stack. As shown in the figure, the stack grows from one side of it. The top represents the value to which is stack is pointing currently. After every push operation, the top will be incremented by one. The top is also known as a stack pointer. When the stack is empty i.e. no elements are present in it the top will point to -1 in our case.

Code:

JavaScript Stack .body-data { border : #81D4FA 2px solid; background-color : #03a9f400; text-align : left; padding-left : 20px; padding-bottom: 20px; height : auto; width : auto; } .resultText { margin: 0 0 3px 0; padding: 0px; display: block;font-weight: bold; } .heading { font-weight: bold; border-bottom: 2px solid #ddd; font-size: 15px; width: 98%; } class Stack { constructor () { this.stack = []; this.top = -1; } push (value) { this.top++; console.log( “Inserting Element: ” + value ); this.stack[ chúng tôi ] = value; } printElements(id) { let elements = “”; for(vari=0;i<=this.top;i++){ elements += this.stack[i] + ” “; } document.getElementById(id).innerHTML += elements; } } let myStack = new Stack(); myStack.push( 5 ); myStack.push( 10 ); myStack.push( 12);myStack.push( 20 ); myStack.push( 35 ); myStack.printElements(“result1”);

Here, We have declared on class for implementing a stack. There are two main variables defined in the class, the stack is an array to store the data, and the top is to maintain the position of the last inserted element into the stack. One method is implemented to push the elements and another is implemented to display the stack elements.

Output: After push operations.

2. isEmpty()

This method will check if the stack is empty and will return true or false. When the stack does not contain any element then the Top will be pointing to -1 i.e., not any element. To check for the stack if it is empty, we can use this pointer. Whenever the Top will be pointing nowhere or to -1 then we can say the stack is empty. We will implement this method in the same way.

Code:

JavaScript Stack .body-data { border : #81D4FA 2px solid; background-color : #03a9f400; text-align : left; padding-left : 20px; padding-bottom: 20px; height : auto; width : auto; } .heading { font-weight: bold; border-bottom: 2px solid #ddd; font-size: 15px; width: 98%; } class Stack { constructor () { this.stack = []; this.top = -1; } push (value) { this.top++; console.log( “Inserting Element: ” + value ); this.stack[ chúng tôi ] = value; } printElements(id) { let elements = “”; for(vari=0;i<=this.top;i++){ elements += this.stack[i] + ” “; } console.log( elements ); document.getElementById(id).innerHTML += elements; } isEmpty(){ return chúng tôi === -1; } } let myStack = new Stack(); myStack.push( 5 ); myStack.push( 10 ); myStack.push( 12); myStack.push( 20 ); myStack.push( 35 ); myStack.printElements(“result1”); document.getElementById(“result2”).innerHTML += myStack.isEmpty();

Output:

3. size

This method will return the size of the stack i.e. how many elements are present in the stack. As the Top variable holds the index at which the last element is stored, we can use this pointer to find out the size of the stack. As the indexing of array is from 0 we can add 1 to the Top and find out the size of the stack.

JavaScript Stack .body-data { border : #81D4FA 2px solid; background-color : #03a9f400; text-align : left; padding-left : 20px; padding-bottom: 20px; height : auto; width : auto; } .heading { font-weight: bold; border-bottom: 2px solid #ddd; font-size: 15px; width: 98%; } class Stack { constructor () { this.stack = []; this.top = -1; } push (value) { this.top++; console.log( “Inserting Element: ” + value ); this.stack[ chúng tôi ] = value; } printElements(id) { let elements = “”; for(vari=0;i<=this.top;i++){ elements += this.stack[i] + ” “; } console.log( elements ); document.getElementById(id).innerHTML += elements; } isEmpty(){ return chúng tôi === -1; } size() { return chúng tôi + 1; } } let myStack = new Stack(); myStack.push( 5 ); myStack.push( 10 ); myStack.push( 12); myStack.push( 20 ); myStack.push( 35 ); myStack.printElements(“result1”); document.getElementById(“result2”).innerHTML += myStack.isEmpty(); document.getElementById(“result3”).innerHTML += myStack.size();

Output:

4. pop

This method will remove the element from the stack. The removed element will be the top element from the stack. As the Top is pointing to the last element, the pop() operation will remove the element at this position. The Top will be decremented by 1 and will point to the element below the previous element.

Code:

JavaScript Stack .body-data { border : #81D4FA 2px solid; background-color : #03a9f400; text-align : left; padding-left : 20px; padding-bottom: 20px; height : auto; width : auto; } .heading { font-weight: bold; border-bottom: 2px solid #ddd; font-size: 15px; width: 98%; } class Stack { constructor () { this.stack = []; this.top = -1; } push (value) { this.top++; console.log( “Inserting Element: ” + value ); this.stack[ chúng tôi ] = value; } printElements(id) { let elements = “”; for(vari=0;i<=this.top;i++){ elements += this.stack[i] + ” “; } console.log( elements ); document.getElementById(id).innerHTML += elements; } isEmpty(){ return chúng tôi === -1; } size() { return chúng tôi + 1; } pop() { if(this.isEmpty()){ return “Stack is Empty”; } else { varval = this.stack[this.top]; this.top –; return val; } } } let myStack = new Stack(); myStack.push( 5 ); myStack.push( 10 ); myStack.push( 12); myStack.push( 20 ); myStack.push( 35 ); myStack.printElements(“result1”); document.getElementById(“result2”).innerHTML += myStack.pop(); myStack.printElements(“result3”);

Output:

5. peek

Code:

JavaScript Stack .body-data { border : #81D4FA 2px solid; background-color : #03a9f400; text-align : left; padding-left : 20px; padding-bottom: 20px; height : auto; width : auto; } .heading { font-weight: bold; border-bottom: 2px solid #ddd; font-size: 15px; width: 98%; } class Stack { constructor () { this.stack = []; this.top = -1; } push (value) { this.top++; console.log( “Inserting Element: ” + value ); this.stack[ chúng tôi ] = value; } printElements(id) { let elements = “”; for(vari=0;i<=this.top;i++){ elements += this.stack[i] + ” “; } console.log( elements ); document.getElementById(id).innerHTML += elements; } isEmpty(){ return chúng tôi === -1; } size() { return chúng tôi + 1; } pop() { if(this.isEmpty()){ return “Stack is Empty”; } else { varval = this.stack[this.top]; this.top –; return val; } } peek() { if(this.isEmpty()){ return “Stack is Empty”; } else { varval = this.stack[this.top]; return val; } } } let myStack = new Stack(); myStack.push( 5 ); myStack.push( 10 ); myStack.push( 12); myStack.push( 20 ); myStack.push( 35 ); myStack.printElements(“result1”); document.getElementById(“result2”).innerHTML += myStack.peek(); myStack.printElements(“result3”);

Output:

6. clear

This method will clear all the elements in the stack. This method will reset the stack pointer i.e Top to -1 and all the elements from the stack will be cleared out. isEmpty() method should return true after this operation.

Code:

JavaScript Stack .body-data { border : #81D4FA 2px solid; background-color : #03a9f400; text-align : left; padding-left : 20px; padding-bottom: 20px; height : auto; width : auto; } .heading { font-weight: bold; border-bottom: 2px solid #ddd; font-size: 15px; width: 98%; } class Stack { constructor () { this.stack = []; this.top = -1; } push (value) { this.top++; console.log( “Inserting Element: ” + value ); this.stack[ chúng tôi ] = value; } printElements(id) { let elements = “”; for(vari=0;i<=this.top;i++){ elements += this.stack[i] + ” “; } console.log( elements ); document.getElementById(id).innerHTML += elements; } clear() { this.top=-1; return “Stack Cleared”; } } let myStack = new Stack(); myStack.push( 5 ); myStack.push( 10 ); myStack.push( 12); myStack.push( 20 ); myStack.push( 35 ); myStack.printElements(“result1”); document.getElementById(“result2”).innerHTML += myStack.clear(); myStack.printElements(“result3”);

Output:

Recommended Articles

This is a guide to JavaScript Stack. Here we also discuss the definition and Javascript stack methods along with different examples and their code implementation. You may also have a look at the following articles to learn more –

Update the detailed information about Stack In C++ Stl With Example on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!