Fixato un bug nella SinglePointerStack e aggiunto due programmi. StackCheckParenthesis che verifica la correttezza delle parentesi tonde e graffe in una stringa utilizzando lo stack. StackInverString che inverte una stringa usando lo stack

This commit is contained in:
2014-03-10 00:15:45 +01:00
parent 84aa1374c7
commit 2d07d22272
3 changed files with 110 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
package com.xgiovio;
import exceptions.EmpyStackException;
import stack.SinglePointerStack;
import java.util.Scanner;
public class StackCheckParenthesis {
/////////////// questo programma controlla se una strng ain input ha correttaemnte le parentesi tonde e quadre
public static void main(String[] args) {
System.out.println("Stringa in input con () e []:");
Scanner reader = new Scanner(System.in);
String word = reader.nextLine();
boolean status = true;
SinglePointerStack<Character> stack = new SinglePointerStack<Character>();
try{
for (int i = 0;i< word.length();i++){
if (word.charAt(i) != '(' && word.charAt(i) != ')' && word.charAt(i) != '[' && word.charAt(i) != ']' ){
continue;
}
if ( word.charAt(i) == '(' ){
stack.push('(');
continue;
}
if ( word.charAt(i) == ')' ){
if (stack.top() == '(' ){
stack.pop();
continue;
} else{
status = false;
break;
}
}
if ( word.charAt(i) == '[' ){
if (stack.isEmpty()){
stack.push('[');
continue;
}
if ( stack.top() == '(' ){
status = false;
break;
} else{
stack.push('[');
continue;
}
}
if ( word.charAt(i) == ']' ){
if (stack.top() == '[' ){
stack.pop();
continue;
} else{
status = false;
break;
}
}
}
if (status && stack.isEmpty()) {
System.out.println("Stringa corretta"); }
else{
System.out.println("Stringa errata");
}
}
catch (EmpyStackException e){
System.out.println("Stringa errata");
}
}
}

View File

@@ -0,0 +1,30 @@
package com.xgiovio;
import exceptions.EmpyStackException;
import stack.SinglePointerStack;
import java.util.Scanner;
public class StackInvertString {
/////////////// questo programma inverte una stringa mediante stack
public static void main(String[] args) {
System.out.println("Stringa in input");
Scanner reader = new Scanner(System.in);
String word = reader.nextLine();
String word_inverted = "";
SinglePointerStack<Character> stack = new SinglePointerStack<Character>();
for (int i = 0;i< word.length();i++){
stack.push(word.charAt(i));
}
for (int i = 0;i< word.length();i++){
word_inverted = word_inverted.concat(String.valueOf(stack.pop()));
}
System.out.println(word_inverted); }
}

View File

@@ -37,6 +37,7 @@ public class SinglePointerStack<E> extends StackRules<E> {
}else{
to_return = stack;
stack = stack.getNext();
--number_of_elements;
return to_return.getElement();
}
}