Stack <String> stackx = new Stack<String>();
Scanner word = new Scanner(System.in);
Scanner countz = new Countz(System.in);
System.out.println("How many time you want to input");
int repeat=countz.nextInt();
for (int i=0;i<repeat;i++){
System.out.println("Data of - "+ (i+1) + ":");
String pintri = word.nextLine();
stackz.push(pintri);
}
System.out.println("Your data: "+stackx);
I want to print the stackx in reverse order, how to do that?
Thank you..
You can print the reversed stack recursively:
void printReversed(Stack<?> stack) {
if (stack.isEmpty()) return;
Object value = stack.pop();
printReversed(stack);
System.out.println(value);
stack.push(value); // restore the stack.
}
This is, of course, working by pushing values into another stack - the call stack.
You use the pop() function to start removing the elements one by one. Stack removes element in LIFO (Last in First out), so naturally the elements will be removed (and accessed by the code) in the reverse order.
If you do not care about performance, you could reverse your Stack, print it, then reverse it back.
Collections.reverse(stackx);
System.out.println("Your data: " + stackx);
Collections.reverse(stackx);
On the other hand, if performance is important, you could use a StringBuilder to print the contents of the Stack data like this
StringBuilder stringBuilder = new StringBuilder();
for (String entry : stackx) {
stringBuilder.insert(0, entry + ", ");
}
stringBuilder.insert(0, "[").replace(stringBuilder.length() - 2, stringBuilder.length() - 1, "]");
If you want to reverse a stack,
Create a new temporary stack
You can use a while loop to pop the top element from stackx and push them onto the temporary stack till stackx becomes empty
Print this temporary stack. It will contain the reversed elements.
Stack<String> reversedStack = new Stack<>();
while(stackx.size() > 0) {
reversedStack(stackx.pop());
}
System.out.println("reversed elements: " + reversedStack);
The input and output are as below:
Input: How many time you want to input
3
Data of - 1:
hello
Data of - 2:
world
Data of - 3:
welcome
Your data: [hello, world, welcome]
reversed elements: [welcome, world, hello]
Just like you do with a list. Just iterate starting with the last index to the first.
for (int i = stackx.size()-1; i>=0; i--) {
System.out.println(stackx.get(i));
}
Using 2 Stacks
Psedudo-code
FirstStack <- add elements (push)
//Before print
SecondStack <- add FirstStack
(while FirstStack is not empty pop element form FirstStack and push into SecondStack
//both Stack's have the same elements but is reverse order
//print from SecondStack
(while SecondStack is not empty pop element and write on screen)
Also for learning purpose you could consider doing your own stack. Algorithm is the same no matter from where is taken the stack implementation.
import java.util.Stack;
public class TestNode {
public static void main(String[] args)
{
TestNode t = new TestNode();
//initial stack
Stack<String> s = new Stack<String>();
s.push("a");
s.push("b");
s.push("c");
//initial stack - same results
//Node s = t.new Node();
//s.push("a");
//s.push("b");
//s.push("c");
//intermediary stack
Node n=t.new Node();
while(!s.empty())
{
n.push(s.pop());
}
n.print();
}
//custom made stack based on linked-nodes
class Node
{
Node n=null;
String data=null;
Node()
{
}
Node(String data, Node n)
{
this.data = data;
this.n = n;
}
public void push(String data)
{
n = new Node(data,n);
}
public boolean empty()
{
if(data==null)
return true;
return false;
}
public String pop()
{
String out = data;
if(out != null)
{
n.data = null;
if(n.n != null)
{
n = n.n;
}
return out;
}
return null;
}
public void print()
{
Node cn = n;
while(cn != null)
{
System.out.println(cn.data);
cn = cn.n;
}
}
}
}
Output
a
b
c
Related
Over the passed couple of hours I have been working on an assigment with no luck in figuring it out. For reference I am going to post the instructions below and then explain what I have done.
Write a Java class that implements the StringSet interface (see
attached text document). One of your instance variables must be an
array of Strings that holds the data; you may determine what, if any
other instance variables you need. You will also need to implement the
required methods, one or more constructors, and any other methods you
deem necessary. I have also provided a tester class that you should be
able to run your code with.
So far I have created an implementation of the interface named MyStringSet. I have put all of the methods from the interface into my implementation and have written the code to what I think will work. My main problem is that I don't know how to put the data from the main method that is called into an array. The user types in a file and and then it is supposed to return word count and other methods. Since the file is being called from the tester class, I need to store that data into an array or an array list which I have already created. Below I have listed my current implementation and the tester class that I use. Any help is greatly appreciated!
My Implementation:
public class MyStringSet implements StringSet {
String[] myArray = new String [] {};
List<String> myList = Arrays.asList(myArray);
//default constructor
public MyStringSet(){
resize(5);
}
// precondition: larger is larger than current Set size
// postcondition: enlarges Set
public void resize(int larger) {
myArray = Arrays.copyOf(myArray, myArray.length + larger);
}
// postcondition: entry is inserted in Set if identical String
// not already present; if identical entry exists, takes no
// action. Calls resize if necessary
public void insert(String entry) {
Set<String> myArray = new HashSet<String>();
Collections.addAll(myArray, entry);
}
// postcondition: removes target value from Set if target is
// present; takes no action otherwise
public void remove(String target) {
if(target != null){
int n = 0;
int index = n;
for(int i = index; i < myArray.length - 1; i++) {
myArray[i] = myArray[i+1];
}
}
}
// precondition: Set is not empty
// postcondition: A random String is retrieved and removed from
// the Set
public String getRandomItem () {
String s = "String is Empty";
if (myArray != null) {
int rnd = new Random().nextInt(myArray.length);
return myArray[rnd];
}
else {
return s ;
}
}
// precondition: Set is not empty
// postcondition: the first item in the Set is retrieved and
// removed from the Set
public String getFirstItem () {
String firstItem = myList.get(0);
return firstItem;
}
// postcondition: returns true if target is present, false
// if not
public boolean contains(String target) {
if (target == null) {
return false;
}
else {
return true;
}
}
// postcondition: returns true if Set is empty, false if not
public boolean is_empty( ) {
if(myArray == null){
return true;
}
else {
return false;
}
}
// postcondition: returns total number of Strings currently in set
public int inventory() {
int total = myList.size();
return total;
}
// postcondition: returns total size of Set (used & unused portions)
public int getCapacity( ) {
int capacity = myArray.length;
return capacity;
}
}
Tester class:
public class SetTester
{
public static void main(String [] args) {
StringSet words = new MyStringSet();
Scanner file = null;
FileInputStream fs = null;
String input;
Scanner kb = new Scanner(System.in);
int wordCt = 0;
boolean ok = false;
while (!ok)
{
System.out.print("Enter name of input file: ");
input = kb.nextLine();
try
{
fs = new FileInputStream(input);
ok = true;
}
catch (FileNotFoundException e)
{
System.out.println(input + " is not a valid file. Try again.");
}
}
file = new Scanner(fs);
while (file.hasNext())
{
input = file.next();
words.insert(input);
System.out.println("Current capacity: " + words.getCapacity());
wordCt++;
}
System.out.println("There were " + wordCt + " words in the file");
System.out.println("There are " + words.inventory() + " elements in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
while (!words.contains(input))
{
System.out.println(input + " is not in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
}
words.remove(input);
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("The first 10 words in the set are: ");
for (int x=0; x<10; x++)
System.out.println(words.getFirstItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("5 random words from the set are: ");
for (int x=0; x<5; x++)
System.out.println(words.getRandomItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
}
}
main problem is that I don't know how to put the data from the main method that is called into an array
You're doing that correctly already, following this simple example
StringSet words = new MyStringSet();
words.insert("something");
However, the contents of the insert method seem incorrect 1) you never check for identical values 2) never resizing 3) Collections.addAll doesn't do what you want, most likely
So, with those in mind, and keeping an array, you should loop over it, and check where the next non-null, non-identical value would be placed
// postcondition: entry is inserted in Set if identical String
// not already present; if identical entry exists, takes no
// action. Calls resize if necessary
public void insert(String entry) {
int i = 0;
while (i < myArray.length && myArray[i] != null) {
if (myArray[i].equals(entry)) return; // end function because found matching entry
i++;
}
if (i >= myArray.length) {
// TODO: resize()
insert(entry); // retry inserting same entry into larger array
}
// updates the next non-null array position
myArray[i] = entry;
}
As far as displaying the MyStringSet class goes, to see the contents of the array, you'll want to add a toString method
I am trying to reverse a stack of type int using recursion. I am able to reverse the first entry, but it shows only zeros when I try to print the supposed reversed stack after the recursion takes place. Here is my code:
//Class to reverse a stack using recursion
class ReverseStack
{
//Global Variables
static int[] stack = new int[5];
static int[] tempStack = new int[5];
private static int size;
//Constructor
public ReverseStack()
{
}
//Functions to for the stack
public static boolean isEmpty()
{
return size == 0;
}
//Function to determine if stack is full
public static boolean isFull()
{
return size == stack.length;
}
//Function to determine size of array
int size()
{
return size;
}
//Function to push entries into stack
public static boolean push(int[] stack, int data)
{
if(isFull())
{
return false;
}
else
{
stack[size] = data;
size++;
return true;
}
}
//Function to remove entries from stack
public static int pop()
{
if(isEmpty())
{
return 0;
}
else
{
size--;
return(stack[size + 1]);
}
}
//Function to print the stack
public static void print(int[] stack)
{
//This prints top to bottom
//Top is the last entry
System.out.println("Top to Bottom");
if(isEmpty())
{
System.out.println("The stack is empty ");
}
else
{
for(int cntr = 0; cntr < size; cntr++)
{
System.out.println(stack[cntr] + " ");
}
}
}
//Function to reverse data recursively
public static void reverseData(int data)
{
//Variables
int tempNum;
int cntr = 4;
int cntr2 = 0;
//Note:
/*
To reverse a stack we need to
1. pass in a number
2. Remove the number
3. Repeat until no numbers are left
4 copy stack
5. print
*/
if(data > stack[cntr - 1])
{
tempStack[cntr2] = data;
cntr--;
cntr2++;
data = stack[cntr - 1];
reverseData(data);
}
}
}
I call this reverseStack function in my program's menu system:
//Function to create a menu system
public static void menu()
{
//Variables
int response;
//Message user
System.out.println("Would you like to: "
+ "\n(1) Reverse a stack using recursion "
+ "\n(2) Draw the Sierpinski Triangle "
+ "\n(3) Draw the Dragon Curve "
+ "\n(4) Recurse through a file/directory system"
+ "\n(5) Recurse through my own recursive function"
+ "\n(6) Quit the program ");
//Save user's response
response = Integer.parseInt(myScanner.nextLine());
//Switch statement for menu options
switch (response)
{
case 1:
{
//Create a new instance of ReverseStack class
ReverseStack rs = new ReverseStack();
//Add data into stack before reversing the stack
rs.push(stack, 10);
rs.push(stack, 20);
rs.push(stack, 30);
rs.push(stack, 40);
rs.push(stack, 50);
//Print stack
rs.print(stack);
//Call function to reverse data set
rs.reverseData(stack[4]);
//Print data set
rs.print(rs.tempStack);
//Return to menu
menu();
break;
}
}
}
Do you know what I may be doing wrong?
Size seems to be always 1 above the index of the last element in the stack, so your pop method should probably be
size--;
return stack[size]; // not stack[size+1]
Also your reverseData function is not working because you are resetting cntr and cntr2 each time the function is called. Those must be global variables.
Maybe try something like
int counter = 0;
public void reverseData (int index) {
if (index > counter) {
int temp = data[index];
data[index] = data[counter];
data[counter] = temp;
counter++;
reverseData(--index);
}
You need to know the next index of your tempStack. Right now it is always 0. So you are only updating the first value and rest are 0s
Change your method
//Function to reverse data recursively
public static void reverseData(int data)
{
//Variables
int tempNum;
int cntr = 4;
int cntr2 = 0;
//Note:
/*
To reverse a stack we need to
1. pass in a number
2. Remove the number
3. Repeat until no numbers are left
4 copy stack
5. print
*/
if(data > stack[cntr - 1])
{
tempStack[cntr2] = data;
cntr--;
cntr2++;
data = stack[cntr - 1];
reverseData(data);
}
}
with this
//Function to reverse data recursively
public static void reverseData(int data, int cntr2)
{
//Variables
int tempNum;
int cntr = 4;
//Note:
/*
To reverse a stack we need to
1. pass in a number
2. Remove the number
3. Repeat until no numbers are left
4 copy stack
5. print
*/
if(data > stack[cntr - 1])
{
tempStack[cntr2] = data;
cntr--;
cntr2++;
data = stack[cntr - 1];
reverseData(data, cntr);
}
}
In your main method, call reverseData(stack[4], 0)
Or create cntr2 as class level variable
If it is a temp stack please not define it as static variable. It is not safe and not good coding behavior.
You used two pointers. The cntr points to the last variable, and the cntr2 points to the first variable. Why not compare them?
For example, keep recursing until the cntr2 less than cntr.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The assignment given to me is this: Create an application to reverse a list by using a linked list based Stack data structure. When you run the program, it asks you to type in an input. When you press Enter, it displays the input in reverse order. You decide the input data type this time.
I made my Node class or Link class, my LinkedList class, LinkedListStack Class, and now i am stuck in the main method.I posted all of my code below in hopes of someone helping me find the error I am making. I looked at other posts but most of them deal with either just reversing a linked list alone, a string, or a linkedlist arraylist.
This is the error I keep getting:
Please enter a word: Hello
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at LinkedStackDemo.main(LinkedStackDemo.java:32)
public class Node
{
public String data;
public Node next;
public Node(String d)
{
data = d;
}
public void displayNode()
{
System.out.println(data + " ");
}
}
Linked List Class
public class LinkedList
{
public Node first;
public LinkedList()
{
first = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insertFirst(String d)
{
Node n = new Node(d);
n.next = first;
first = n;
}
public String deleteFirst()
{
//if(first == null)
//{return first;}
Node temp = first;
first = first.next;
//temp.next = null;
//return temp;
return temp.data;
}
public void displayNode()
{
Node current = first;
while(current != null)
{
current.displayNode();
current = current.next;
}
System.out.println(" ");
}
}
Linked Stack Class
public class LinkedListStack
{
private LinkedList node;
public LinkedListStack()
{
node = new LinkedList();
}
public boolean isEmpty()
{
return node.first == null;
}
public void push(String data)
{
node.insertFirst(data);
}
public String pop()
{
return node.deleteFirst();
}
public void displayStack()
{
System.out.println("Reversed order: ");
node.displayNode();
}
}
My main method (this is where i am getting very stuck)
import java.util.Scanner;
import java.util.Stack;
public class LinkedStackDemo
{
public static void main(String []args)
{
LinkedListStack s = new LinkedListStack();
LinkedList s1 = new LinkedList();
String input;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a word: ");
input = scan.nextLine();
s.push(input);
//String reverse = new StringBuffer(s.push(input)).reverse().toString();
//System.out.println(reverse);
for (int i = 1; i <= input.length(); i++)
{
while(i<=input.length())
{
String c = input.substring(i,i-1);
s.push(c);
}
//System.out.println("The stack is:\n"+ s);
s.displayStack();
}
}
}
I fixed the most recent problem but now it prints the code vertically instead of horizontally, this was my most recent problem.
This how it prints it out, the desired output would be to print the reverse like this, " olleH "Please enter a word: Hello Reversed order: H Hello Reversed order: e H Hello Reversed order: l e H Hello Reversed order: l l e H Hello Reversed order: o l l e H Hello
Taking out the System.out.println(" "); from displayNode; did not fix the problem for it printing out vertically.
The vast majority of the code here is totally irrelevant to the problem you describe. The only relevant bit is this:
for (int i = 1; i <= input.length(); i++)
{
while(i<=input.length())
{
String c = input.substring(i,i-1);
s.push(c);
}
//System.out.println("The stack is:\n"+ s);
s.displayStack();
}
The actual problem that you're seeing is the exception caused by passing in i and i-1 to String.substring. As it says in the Javadoc (emphasis mine):
[Throws] IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
So, you need to call something else, like input.substring(i-1, i).
But there's another problem here: your while loop will never terminate, because i and input never change, so i<=input.length() never changes. As such, you'd just keep on pushing c into the stack until you run out of memory.
This while loop is simply unnecessary; remove it.
So I have this code:
public class SortedIntList extends IntList
{
private int[] newlist;
public SortedIntList(int size)
{
super(size);
newlist = new int[size];
}
public void add(int value)
{
for(int i = 0; i < list.length; i++)
{
int count = 0,
current = list[i];
if(current < value)
{
newlist[count] = current;
count++;
}
else
{
newlist[count] = value;
count++;
}
}
}
}
Yet, when I run the test, nothing prints out. I have the system.out.print in another class in the same source.
Where am I going wrong?
EDIT: Print code from comment:
public class ListTest
{
public static void main(String[] args)
{
SortedIntList myList = new SortedIntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
}
}
EDIT2: Superclass from comment below
public class IntList
{
protected int[] list;
protected int numElements = 0;
public IntList(int size)
{
list = new int[size];
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else {
list[numElements] = value; numElements++;
}
}
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Let's walk through the logic of how you want it to work here:
first you make a new sorted list passing 10 to the constructor, which make an integer array of size 10.
now you call your add method passing 100 into it. the method sets position 0 to 100
now you add 50, the method sets 50 in position 0 and 100 in position 1
now you add 200, which gets placed at position 2
and you add 25. which gets set to position 0, and everything else gets shuffled on down
then your method will print out everything in this list.
So here are your problems:
For the first add, you compare current, which is initialized at 0, to 50. 0 will always be less than 50, so 50 never gets set into the array. This is true for all elements.
EDIT: Seeing the super class this is how you should look to fix your code:
public class SortedIntList extends IntList
{
private int[] newlist;
private int listSize;
public SortedIntList(int size)
{
super(size);
// I removed the newList bit becuase the superclass has a list we are using
listSize = 0; // this keeps track of the number of elements in the list
}
public void add(int value)
{
int placeholder;
if (listSize == 0)
{
list[0] = value; // sets first element eqal to the value
listSize++; // incriments the size, since we added a value
return; // breaks out of the method
}
for(int i = 0; i < listSize; i++)
{
if (list[i] > value) // checks if the current place is greater than value
{
placeholder = list[i]; // these three lines swap the value with the value in the array, and then sets up a comparison to continue
list[i] = value;
value = placeholder;
}
}
list[i] = value; // we are done checking the existing array, so the remaining value gets added to the end
listSize++; // we added an element so this needs to increase;
}
public String toString()
{
String returnString = "";
for (int i=0; i<listSize; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Now that I see the superclass, the reason why it never prints anything is clear. numElements is always zero. You never increment it because you never call the superclass version of the add method.
This means that the loop in the toString method is not iterated at all, and toString always just returns empty string.
Note
This is superseded by my later answer. I have left it here, rather than deleting it, in case the information in it is useful to you.
Two problems.
(1) You define list in the superclass, and presumably that's what you print out; but you add elements to newList, which is a different field.
(2) You only add as many elements to your new list as there are in your old list. So you'll always have one element too few. In particular, when you first try to add an element, your list has zero elements both before and after the add.
You should probably have just a single list, not two of them. Also, you should break that for loop into two separate loops - one loop to add the elements before the value that you're inserting, and a second loop to add the elements after it.
Pretty simple idea, I am just not sure why it won't work. I am getting an error when I call Stack b = new Stack(5); in main.
Here is main
public class Test {
public static void main(String[] args) {
Stack b = new Stack(5);
b.push('a');
b.push('b');
b.push('c');
b.printStack();
}
}
Here is my stack class
public class Stack {
char[] stack;
int items;
public Stack(int size) {
stack = char[size];
items = 0;
}
public void push (char add){
if (items == stack.length) {
System.out.println("Stack is full");
}
else {
stack[items] = add;
}
}
public void printStack() {
if (items == 0)
return;
else {
for (int i = 0; i < items; i++)
System.out.println(i);
}
}
}
One thing is:
public Stack(int size) {
stack = new char[size];
//^^^you missed new
items = 0;
}
Meanwhile
stack[items] = add; //should also increment items
You need to new up your array.
I can see that your push doesn't increment the items count. When you push onto your stack, you should also increment the count.
in your constructor use
stack = new char[size];
You are not using the new keyword when creating your stack array in the constructor.
Furthermore, your push() method does not increment items, and thus will simply constantly overwrite the first element of the stack array.
Finally, your printStack() method will not function as you expect it to. Rather, it will print incremental digits up to the number 5. You will need to change the print statement for it to work.
System.out.println(stack[i]);