I have a question how to design a stack without using list or array?
This is one question that I want to think about as I want to better understand stack.
I have a question how to design a stack without using list or array? This is one question that I want to think about as I want to better understand stack. |
|||
closed as too broad by gnat, MichaelT, World Engineer♦ Apr 18 at 13:43There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question. |
|||
|
A stack can either be empty (which is really easy to write), or it can not be empty in which case it has a top item and a pointer to the rest of the stack. To implement a stack without using java library,
|
|||||
|
A stack is really just an interface, which provides at least the following operations:
The underlying implementation can be anything that satisfies these operations. Arrays and lists are common implementations for stacks, but you could create an (inefficient) stack using a hash table, or files on disk, or even numbered pieces of paper scattered around a room. As long as the ability to push and pop are available somehow, it's a stack. |
|||||||||
|
You dont have to use an array or a list, you can create a simple stack by doing the following:
|
|||||
|
Since you tag the question as java we solve the question with.....Objects! We're actually pretty much going to be implementing a singularly linked list. A stack can either be empty (which is really easy to write), or it can not be empty in which case it has a top item and a pointer to the rest of the stack. Below is code for an immutable stack (one in which pushing or popping returns a new stack instead of modifying the existing one). You'll have to forgive the formatting, I don't know how to correctly enter the code into the editor here. First you have an interface saying what constitutes a stack
There are 2 kinds of IStacks. Those which are empty, and those which aren't. Let's look at the EmptyStack first because it's easier.
Now let's look at a Stack which isn't empty.
Let's try using it
Output from the test is
|
|||
|
Conceptually speaking, a stack is a linked list without random access and only one point of entry: the top, whereas a list often has random access and two points of entry: the front and the back. While there usually is a T peek(), peek can't be used for manipulation of the contents. Random access is usually explained as the ability to manipulate at any given point in the collection. So if you're saying without using a list, do you mean without using a Java API List class as a basis for your work, or really not using a list? The latter is almost impossible, as it basically is a list, and implementing in another manner would be an exercise comparable to making a Rube Goldberg machine. |
||||
|