Hesper Hesper - 1 month ago 20
Java Question

Stack implementation

I am new in programming and I have a problem in stack implementation.
My question is what is difference between array and stack in implementation. What is the exact syntax to define a stack in programming language like Java.

Most people use arrays for stack implementation. If array and stack are two different data structure, why we use array to implement a stack? How we can implement a stack without an array?

If someone can provide an example, please help me.

Answer

Amit has given the syntax for defining a stack. As a specific example, in Java you can define integer stacks as follows: Stack<Integer> intStack = new Stack<Integer>(); Now you can use all the methods of stacks like intStack.push() and intStack.pop(). Useful link: http://en.wikibooks.org/wiki/Java_Programming/Collection_Classes

The reason why stacks are also implemented using arrays or linked lists is that not all languages have the stack data structure in-built. For example C doesn't have have it and the only way you can implement a stack is indirectly (using arrays, linked lists, etc. ) http://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Array . In Java things are easier since you can directly use the stacks implementation.