So I tried to implement a stack with just one queue and it appears to work, but I'm not sure if there's something wrong with it since most of the solutions I've seen online use two queues. Can anyone tell if me if there are problems with my implementation?
public class MyStack<T> {
/**
* #param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
Output:
4
3
2
1
null
Your solution is inefficient because you have to loop through the whole stack every time you pop something from it. (Effectively you have to traverse the whole linked list, before removing the element that was at the end.)
Edit: Java's linked list is doubly linked anyway, so this is entirely pointless.
You should use either a Stack or a Deque or even a LinkedList.
Implementing your own is just ... pointless. Unless of course (as #bas suggests) you are doing a course on data structures in which case you should go Commando and implement your own structure from scratch. Using another structure because it is nearly like the one you are trying to make is like using a hammer with screws.
If you really need to implement something yourself something like this should work:
public class Stack<T> {
private Entry top = null;
private class Entry {
final Entry up;
final T it;
public Entry(Entry up, T it) {
this.up = up;
this.it = it;
}
}
public void push ( T it ) {
top = new Entry(top, it);
}
public T pop () {
if ( top == null ) {
throw new EmptyStackException();
}
T it = top.it;
top = top.up;
return it;
}
}
NB: This may not be thread safe.
There is absolutely no reason a stack should use two queues. As a matter of fact, it only needs to keep track of one top-node that references the nodes below it.
The code seems to work, but as nachokk said, this is not the site for code review. This site is ment if you run into errors and require assistance.
You must use two queues ONLY when you have basic queues operations, like enqueue and dequeue. When you can use other methods, especially iterating over queue, you can do it with only one queue, like you did.
Related
Is there any way I can return a value from a loop and continuing from where I left off ?
In the following snippet, I want to return the current value of currVm. But I am unable to do so.
In the innermost loop of the snippet :
while(c <= currVm) {
allocatedVm(currVm);
c++;
}
a function named allocatedVm is called. I want to return the value of currVm and start again from where I left off. Is there any way out ?
#Override
public int getNextAvailableVm() {
Set<String> dataCenters = confMap.keySet();
for (String dataCenter : dataCenters) {
LinkedList<DepConfAttr> list = confMap.get(dataCenter);
Collections.sort(list, new MemoryComparator());
int size = list.size() - 1;
int count = 0;
while(size >= 0) {
DepConfAttr dca = (DepConfAttr)list.get(count);
int currVm = dca.getVmCount();
int c = 0;
while(c <= currVm) {
allocatedVm(currVm); // RETURN currVm
c++;
}
count++;
size--;
}
}
}
The best approach would probably be to write a method returning an Iterable<Integer>. That's not as easy in Java as it is in languages which support generator functions (e.g. C# and Python) but it's still feasible. If the code is short, you can get away with a pair of (nested) anonymous inner classes:
public Iterable<Integer> foo() {
return new Iterable<Integer>() {
#Override public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
// Implement hasNext, next and remove here
};
}
};
}
In your case I'd be tempted to break it into a separate non-anonymous class though, just for simplicity.
Anyway, the point of using Iterable is that an Iterator naturally has state - that's its purpose, basically. So it's a good fit for your requirements.
Another rather simpler approach would be to return all of the elements in one go, and make the caller perform the allocation on demand. Obviously that doesn't work well if there could be a huge number of elements, but it would be easier to understand.
not sure i understand what you need, but:
if you wish to notify the caller of the method that you've got a value during the running of the method, but don't wish to exit the method just yet, you can use listeners.
just create an interface as a parameter to your function, and have a function inside that will have the object as a parameter.
example:
interface IGotValueListener
{
public void onGotValue(MyClass obj);
}
public int getNextAvailableVm(IGotValueListener listener)
{
...
if(listener!=null)
listener.onGotValue(...);
}
now , for calling the method, you do:
int finalResult=getNextAvailableVm(new IGotValueListener ()
{
... //implement onGotValue
};
You can return from anywhere in your method , by just putting the return keyword. If you want to put a functionality to resume ur method from different places then u need to factor ur method in that way. You can use labels and if statements, set some static variables to mark the last execution place. If your application is not multi-threaded then u need not to worry with the use of static variable synchronization. Also if your method is too big and becoming hard to follow/read, then think about breaking it into smaller ones.
E.g.
I have a queue
void someMethod() {
history.add(new Sample(time, data));
...
traverse(history);
}
void traverse(Queue<Sample> history) {
for(int i=0; i<history.size(); i=i+10) {
history.get(i)... // ???
}
}
class Sample {
long time;
double data;
}
The concerns are that
I don't want to destroy this queue by calling traverse().
Traverse the queue in a given step, say 10 here.
Any simple and nice solution?
for (Sample s : history)
doStuff(s);
This is called the enhanced for-loop; you can read more about it here.
Queue implements Iterable, so a simple loop will traverse it:
for (Sample sample : history)
An Iterator is another way to do it, with more control (can destroy it if you want to), but more verbose.
If you just want to iterate, use a for-each loop or directly a for loop with an Iterator. This doesn't consume the queue.
If you need to iterate with a step, you can use this pattern. It works generally with any Iterable. Putting the skipping into a separate reusable method makes the code more clear than having two nested for loops.
public static void main(String[] args) {
Queue<Sample> history = ...
int step = 10;
for (Iterator<Sample> it = history.iterator();
it.hasNext(); skip(it, step - 1)) {
// note that we skipped 1 less elements than the size of the step
Sample sample = it.next();
// stuff
}
}
static void skip(Iterator<?> iterator, int count) {
for (int i = 0; i < count && iterator.hasNext(); i++) {
iterator.next();
}
}
LinkedList<Sample> h = (LinkedList<Sample>) history;
for(int i=0; i < h.size(); i+=step) {
h.get(i).memory ...
}
I just realized this approach, haven't tried it yet.
As nullptr pointed out, the condition for above code is that the Queue is implemented as a LinkedList. (which is my case: Queue<Sample> history = new LinkedList<Sample>();)
This question already has answers here:
Closed 10 years ago.
I'm trying to create a Stack to take a string and add each of the strings characters to it, but I was told it would be far more efficient use a LinkedList. How would I use a LinkedList to create and manipulate a stack?
An example would be very appreciated!
Ok, the problem is that you're not using First at all. Try the following:
public class Example
{
private LinkedList aList = new LinkedList();
public void push(char c) {
aList.addFirst(c);
}
public Object pop() {
return aList.removeFirst();
}
public boolean empty() {
return aList.isEmpty();
}
public static void main(String[] args) {
Stack exmpStack = new Stack();
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
exmpStack.push(ranString.charAt(i));
}
while (!exmpStack.empty()) {
System.out.print(exmpStack.pop());
}
}
}
Because you never use First it's always null - so your loop never runs at all! Instead of using that at all, just use the build in isEmpty() function.
Edit: Of course, you don't really need those functions at all - the following will work fine:
public class Example
{
private LinkedList aList = new LinkedList();
public static void main(String[] args) {
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
aList.push(ranString.charAt(i));
}
while (!aList.isEmpty()) {
System.out.print(aList.pop());
}
}
}
Now this is still a bit unsafe - you can go one step further by using the following:
private LinkedList<Character> aList = new LinkedList<>();
That way it's a bit safer, and returns Characters instead of Objects - and Characters can be implicitly cast to char :)
Java's LinkedList is a doubly linked list, with efficient accessors to get, add, and remove elements both at the end and at the head of the list, so you can use those methods to emulate a stack.
A LinkedList provides more operations that that of a stack.
You use a stack for pushing and popping your characters of your string. However you can only retrieve the character in the order that opposite the way you insert your string. So are you sure if you want this behaviour.
A linkedlist allows you to add/retrieve your data either from head / tail.
LinkedList is indeed more efficient, as Stack comes with synchronized methods by virtue of its reliance on Vector. In single-threaded applications, using the latter means paying the synchronization price for no benefit. Even in multi-threaded applications, you may want more control over synchronization.
Here's a possible LinkedList based solution. Please note the use of composition instead of inheritance. This will give you a well behaved Stack that cannot be abused by using List-related methods.
class MyStack<T> {
private List<T> list = new LinkedList<T>();
public void push(T object) { list.add(0, object); }
public T pop(T object) {
if (isEmpty()) throw new NoSuchElementException();
return list.remove(0);
}
public boolean isEmpty() { return list.isEmpty(); }
}
Nonetheless, if your stack is meant only for string characters as your question suggests, you might want to emulate a stack directly on a dynamic character array. I will leave that as an exercise to the reader, or I may provide it in a future edit.
Here is the sample: Stack implementation. Hope it helps.
It is done with C# but you get the idea
I recall seeing, somewhere, an example that stepped through String args[] by deleting the lowest numbered value(s)
public static void main( String args[]) {
while (args.length > 0 ) {
// do something and obliterate elements from args[]
}
}
Obviously, a variable tracking current position in args and compared to args.length will do it; or an ArrayList made from args[]'s contents, with argsAL.size(). Am I mis-remembering an ArrayList example? I know this is a borderline question, the likely answer is, "No, there isn't and there shouldn't be either!". Maybe I'm over-focused...
Bill
No, there isn't and there shouldn't be either! Deleting from the front of an array would be a needlessly expensive way to do this.
You might be thinking of many scripting languages having a shift operator to dequeue the next element (perl, bash, etc).
Edit: Just for posterity, here's a pretty simple implementation of Queue that would allow you to "fake" the same functionality (i.e. encapsulate the cursor):
class ArrayQueue<E> extends AbstractQueue<E> {
private int cursor = 0;
private final E[] data;
public ArrayQueue(E[] data) {
this.data = data;
}
private boolean inRange() {
return cursor < data.length;
}
#Override
public E peek() {
return inRange() ? data[cursor] : null;
}
#Override
public E poll() {
return inRange() ? data[cursor++] : null;
}
#Override
public boolean offer(E e) {
throw new UnsupportedOperationException();
}
#Override
public void clear() {
cursor = data.length;
}
#Override
public Iterator<E> iterator() {
//ommitted for brevity
}
#Override
public int size() {
return data.length - cursor;
}
}
Usage:
public static void main(String[] args) throws Exception {
Queue<String> argQ = new ArrayQueue<String>(args);
String command = argQ.poll();
String target = argQ.poll();
}
Warning: Untested
You should really use an argument parser. My favorite is Java Simple Argument Parser (JSAP).
There is no reason to manipulate the args[] array directly. I use JSAP even for the most basic command line programs, because eventually they aren't "basic" anymore.
If you plan on popping off elements, don't use an array list since the whole array will need to be copied a bunch of times. Instead, do something like this:
public static void main(String args[]) {
for (String arg : args) {
// consume arg somehow
}
}
Just use a for loop, except when you really love arraycopy's.
From a performace view it doesn't matter either, most command lines don't except more than 32k chars and I don't think your app is usually used for 16k args on the command line.
...Am I mis-remembering an ArrayList example?..
Probably or some other programming language.
Some of them have the method shift which when invoked does that, gives you the 0th element and removes it, something like:
main( args: Array[String) {
name = args.at(0)
args.shift
lastName = args.at(0)
args.shift
}
It would be a weird way to do it. Technically more expensive, but unless you have some crazy big command line, that really isn't even a consideration.
It has been suggested already to use a loop and this can definitely work.
For better control of command line options check out java-getopt.
You should really use a List, perhaps using java.util.Arrays.asList(args). Then you have ordered traversal and easy removal of front and back elements.
Question :
b) A Stack is a last-in first-out (LIFO) data structure. Write a Java class
Stacklnt that stores a stack of integers using an alray as its private data
structure. A Stacklnt has:
A maximum size, which is set when a Stacklnt object is created.
An exception should be thrown if the size is outside the range 10 to .
1000
A method push, to add a value to the top of the stack. An exception
should be thrown if the stack is full when push is called.
A method pop, to remove and return the value at the top of the stack.
An exception should be thrown if the stack is empty when pop is
called.
c) Write some example code to show how your class Stacklnt from part (b)
should be used. Include examples of normal usage and for all cases when
exceptions are thrown.
Ok so basically this is a question im trying to solve and would really really appreciate some help.
exceptions are in this form
// Throw an exception!
public T pop() throws EmptyStackException
{
if (contents.size() == 0)
{ throw new EmptyStackException(); }
else
{ return contents.remove(0); }
}
me so far :
public class Stack {
private int top;
private int[] storage;
Stack(int capacity) {
if (capacity <= 0)
throw new IllegalArgumentException(
"Stack's capacity must be positive");
storage = new int[capacity];
top = -1;
}
void push(int value) {
if (top == storage.length)
throw new StackException("Stack's underlying storage is overflow");
top++;
storage[top] = value;
}
int peek() {
if (top == -1)
throw new StackException("Stack is empty");
return storage[top];
}
}
You're trying to do the whole program at once, which is a bit difficult because there could be many trivial syntax errors, and any ONE of them will cause it to not compile.
So, the recommendation is to take baby steps - you'll probably hear this a lot. It goes like this (assuming you haven't written any code yet):
1) Edit your StackInt.java file so that it only contains the following:
class StackInt {
}
2) Compile it.
2a) If it doesn't compile correctly, fix those errors FIRST before adding new code.
3) Add a small amount of new code. Say, a main() method. Your class now looks like this:
class StackInt {
public static void main(String[] args) {
System.out.println("hello world!");
}
}
4) Compile it. Then run it. If it doesn't compile, fix those errors before continuing. If it compiles, then run it. You should see it print out "hello world!". This tells you it was run successfully. If there's no output, then you know somethings wrong, and you'll have to fix that before continuing.
In this way, you take "baby steps" - you add just a small amount of code each time, and then compile it and run it to make sure it works the way you expect.
Doing programs this way has been really helpful to me. You can work on one method at a time, instead of typing ALL of them in and wondering where it fails. I recommend it.
Edit:
Since you already have code written, you could adapt this "baby steps" approach by commenting out most of your code so that you don't waste it. Use /* and */ to comment out entire sections - this way the compiler ignores it and you can go about trying out one piece at a time. It looks like this:
class StackInt {
/*
this is "commented out"
push(int number) {
}
*/
public static void main(String[] args) {
System.out.println("hello world!");
}
}
Hope this helps.
read Fundamentals of OOP and Data Structures in Java - Richard Wiener
Chapter 11 is all about stacks and queues
As an answer to your last comment to your question: your syntax is not bad. I cleaned your code up a bit and, once you've implemented the StackException class and the pop method, it should compile correct:
public class Stack {
private int top;
private int[] storage;
public Stack(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException(
"Stack's capacity must be positive");
}
top = -1;
storage = new int[capacity];
}
public void push(int value) {
if (top == storage.length) {
throw new StackException("Stack's underlying storage is overflow");
}
top++;
storage[top] = value;
}
public int peek() {
if (top == -1) {
throw new StackException("Stack is empty");
}
return storage[top];
}
public int pop() {
// TODO
}
}
Here's what you should do:
Create a class named Stacklnt**.
Use an array of integers int[] as an instance variable.
Use the constructor of the class to initiate the array with a given size as the constructor's parameter. You have to check that this size is in the range (10 to 1000)
make the two instance methods push and pop. You can use an integer variable as a pointer to the current array position, so you increase it when push is called, and you decrease it when pop is called. You have to make sure this pointer doesn't exceed the limits (i.e. doesn't go lower than zero, and doesn't go higher than the size).
Read over your question once more and look for all of the things you have not done.
you have not put in the method pop
you have not followed the example of exceptions given by the sample pop()
you have not check for range properly
you have not written a main method which instantiates a stack and tests it