How to use data structure – Stack

Know how to use data structure is essential for productive developer. Before jump into data structure use case scenario we have to understand what is data structure and how to use them in our daily life.

This article is the part of Stack data structure series. Please take a look at Stack’s article for a better understanding.

Data Structure – part-2-Stack

We will discuss two different examples of using Stack:

  • Multiple base conversion
  • Palindromes

Let’s take a look on the Stack implementation code.

Multiple base conversion

Stack can be used to convert a number from one base to another. Given a number, n, which we want to convert to a base, b, here is the algorithm for performing the conversion:

  1. The rightmost digit of n is n%b. Push this onto the stack
  2. Replace n with n/b
  3. Repeat step 1 & 2 until n=0
  4. Pop the stack until empty

This algorithm will work only with bases 2 through 9.

Lets implement the code using Stack class functions.

Now, our implementation has done. It is time for testing.

Palindromes

A palindrome is a word, phrase, or number that is spelled the same forward and backward. For example, “dad” is a palindrome; “racecar” is a palindrome; “A man, a plan, a canal: Panama” is a palindrome if you take out the spaces and ignore the punctuation; and 1,001 is a numeric palindrome.

Lets implement the code using Stack class functions.

A stack can be used in many more operations and can solve complex computational problems. Hope, given examples, give you some hints, how to use stacks. Feel free to contact me.

Learn more about data structure.