Files
unisa_strutture_dati_2013_2014/esercizi/static_methods.java

194 lines
4.5 KiB
Java

package esercizi;
import queue.NodeQueue;
import queue.Queue;
import stack.ArrayStack;
import exceptions.*;
/**
* Created with MONSTER.
* User: xgiovio
* Date: 13/04/2014
* Time: 22:19
*/
public class static_methods {
// inver a string using a stack
public static String inverti (String s){
ArrayStack<Character> a = new ArrayStack<Character>();
for (int i = 0 ;i< s.length();i++){
a.push(s.charAt(i));
}
String to_return = "";
for (int i = 0 ;i< s.length();i++){
to_return += a.pop();
}
return to_return;
}
// verify is a string of [ and ( is correct using a stack
public static boolean checkParentheses (String s) {
ArrayStack<Character> a = new ArrayStack<Character>();
for (int i = 0 ; i< s.length();i++){
if (s.charAt(i) == '('){
a.push(s.charAt(i));
continue;
}
if (s.charAt(i) == ')'){
if (a.isEmpty() || a.top() != '('){
return false;
} else {
a.pop();
}
continue;
}
if (s.charAt(i) == '['){
if ( a.isEmpty() || a.top() != '(') {
a.push(s.charAt(i));
} else {
return false;
}
continue;
}
if (s.charAt(i) == ']'){
if (a.isEmpty() || a.top() != '['){
return false;
} else {
a.pop();
}
continue;
}
}
if (a.isEmpty()){
return true;
}else {
return false;
}
}
// verify is a string is palindrome using a stack
public static boolean isPalindrome (String s){
ArrayStack<Character> a = new ArrayStack<Character>();
if (s.length() < 2){
return true;
}else {
boolean pari;
if (s.length() % 2 == 0) {
pari = true;
} else {
pari = false;
}
for (int i= 0 ;i < s.length();i++){
if (!pari){
if (i <= s.length()/2){
a.push(s.charAt(i));
if (i == s.length()/2 ){
a.pop();
}
continue;
}
} else {
if (i <= (s.length()/2) -1){
a.push(s.charAt(i));
continue;
}
}
if (s.charAt(i) != a.pop()){
return false;
}
}
return true;
}
}
// extract the k element from a Queue Q. k should be >= 0
public static Integer extract (Queue<Integer> Q, int k) throws NotEnoughElements {
if (Q.size() <= k) {
throw new NotEnoughElements();
} else {
Integer t = null ;
for (int i = 0 ;i< Q.size();i++){
if (i == k){
t = Q.front();
}
Q.enqueue(Q.dequeue());
}
return t;
}
}
// invert a Queue without recursive methods
public static <E> void reverse (Queue<E> Q){
NodeQueue<E> newq = new NodeQueue<E>();
for (;Q.size()> 0;){
for (int i = 0;i< Q.size() - 1;i++){
Q.enqueue(Q.dequeue());
}
newq.enqueue(Q.dequeue());
}
int size = newq.size();
for (int i = 0;i<size;i++){
Q.enqueue(newq.dequeue());
}
}
// invert a Queue with recursion
public static <E> void recReverse (Queue<E> Q){
if (Q.size()>1){
E t = Q.dequeue();
recReverse(Q);
Q.enqueue(t);
}
}
// search element x in Queue Q . WARNING THIS FUNCTION ALTER THE ORIGINAL QUEUE Q
public static <E> boolean isContained (Queue<E>Q,E x){
if (Q.size() > 0){
E t = Q.dequeue();
if (t==x){
return true;
}
else{
return isContained(Q,x);
}
}else {
return false;
}
}
}