I have to create a method peek MidElement , so as return the middle element of the stack .
So do I have to use an ArrayList, or TORTOISE-HARE algo .
The following is my Class , which has a method named peekMidElement.
How do I reference Size() to the ArrayList .
When I compile the following , I am getting IndexOutOFBoundsExcption at ArrayList.RangeCheck(UnknownSource) & at ArrayList.get(UnknownSource)
public class SortableStack<E extends Comparable<E>> implements ISortableStack<E> {
private int N;
private Node first;
private ArrayList<E> listOne = new ArrayList<E>();
/* I have to reference the Stack to array list
which I am going use for finding the size of the stack */
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public E peekMidElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(listOne.size()/2);
}
I cannot see how the code snippet you gave can throw an IndexOutOfBoundsExcption at the point you have indicated. I conclude that:
the code snippet is not the actual code (e.g. it has been spliced together from a larger class, leaving out some crucial details), or
the exception is not thrown at the place you indicated, or
... this class (which is not thread-safe) is being used in a multi-threaded application without adequate synchronization. The scenario is that some other thread deletes a bunch of elements from listOne at exactly the wrong moment. This unlikely, and if it was the cause, the failure would only occur very occasionally.
Related
First of all, let me say that this is an assignment for a class where we have been tasked with writing our own doubly linked list class and cannot use anything from Java SE (e.g. the LinkedList class). We have to make our code work with a provided driver class. I am not asking for anyone to do the homework for me, I am simply asking for some kind of clarification as to how exactly to implement these methods, since I have struggled with this on and off over the past few days.
We have been provided with an Interface, textEditor.java that provides methods which will be utilized by the driver class, driver.java. These methods include the typical insert, et. al. but my concern is the insertAfter(int lineNum, E line) method and its counterpart, insertBefore. I have not been able to get these to work because comparing int to E, despite my best efforts and reading through several Java texts for guidance.
Below is the code in the DoublyLinkedList.java file, as provided at onset. I would like to know how I can implement some kind of indexing and checking in order to be able to make an insertion following or preceding the line entered by the user/driver class.
public class DoublyLinkedList<E> implements TextEditor<E>
{
Node<E> head, tail;
public DoublyLinkedList()
{
head = null;
tail = null;
}
public boolean isEmpty()
{
return (head == null);
}
public void insert(E line)
{
}
public void insertAfter(int lineNum, E line)
{
}
public void insertBefore(int lineNum, E line) throws IndexOutOfBoundsException
{
}
public void deleteByPosition(int position)
{
}
public void printNode(int position)
{
}
public void printAllNodes()
{
}
}
I have not been able to do this, and having tried several things over several hours, I have given up hope of being able to do it. If I don't find help here or still can't get these methods to work, I will be speaking with my instructor. It may simply be that I am overthinking the problem, and I hope that that is the case.
I'm assuming that your Node class looks like this :
class Node<E> {
private Node next;
private E value;
[...]
}
You can add an attribute in your DoublyLinkedList class, in which you keep the number of Node that your list contains.
Then, if you want the Nth element of your list, you can do this :
private Node getNthElement(int n) {
Node node = head;
for (int i=0; i<n; i++) {
node = node.next;
}
return node;
}
These methods should also check if there are enough elements in the list, etc. But this is the main idea.
I have a generic LinkedStack class with a LinkedStack reversed method
It creates a new LinkedStack say newLinkedstack and pushes items from the current stack by popping them. So at the end of the operation the current stack is left empty and newLinkedStack contains the same items/elements that were in "this" stack only in reverse order.
My code compiles but when I create and fill up a stack and then print out the contents,
I only get one result.
public LinkedStack<T> rev()
{
LinkedStack<T> revStack=new LinkedStack<T>();
//final int SIZE=this.size();
while(!(this.empty)){//for(int i=0;i<SIZE;i++)
{
revStack.push(this.pop());
}
return revStack;
}
For example
LinkedStack<String> newLS = new LinkedStack<String>();
newLS.push("noid");
newLS.push("enilec");
newLS.push("River");
newLS.push("Healing");
newLS.push("Pain");
and newLS.rev() returns Pain instead of a reversed stack
UPDATE
Here's my pop method
public T pop()
{
T element=peek();
top=top.next;
return element;
}
I have two push methods this one moves every element from input stack to current stack leaving input stack from argument empty
public void push(LinkedStack<T> stack){
//int SZE = stack.size();
while(!(stack.empty())){//formally for(int i=0;i<SZE;i++){
this.push(stack.pop());}}
Here's my other push method
public void push(T element)
{
top=new Node<T>(item,top);
}
I'm not sure where LinkedStack came from, but it seems that the bug is being caused by that class's implementation.
You'll have to post more source code if you want more specific help.
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.
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
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