Tuesday, 15 June 2010

stack - Java palindrome checker using queue AND restoring queue to original state -



stack - Java palindrome checker using queue AND restoring queue to original state -

i've written long , complicated method checking if list of elements in queue palindrome. know can improved, goal right past tests in practice-it. i've passed 9 out of 10, test can't seem pass odd elements/not palindrome.

for example: front end [5, 10, -1, 4, 3, 2, 2, 4, -1, 10, 5] back. expected output should false. output true.

also, unlike other tests, elements in queue aren't beingness displayed. unlike previous questions asked similar problem, queue must restored original state. here code far:

public static boolean ispalindrome(queue<integer> q) { stack<integer> s = new stack<integer>(); int size = q.size(); int extra = 0; if(q.isempty()) return true; else  if (size % 2 == 0) { for (int i = 0; i < size / 2; i++) { s.push(q.remove()); }       while (!s.isempty()) {  // while stack not empty: if (s.peek() != q.peek()) { int first = s.pop(); s.push(q.remove()); s.push(first); while (!q.isempty()) s.push(q.remove()); while (!s.isempty()) { q.add(s.pop()); } return false; } else { while (!q.isempty()) s.push(q.remove()); while (!s.isempty()) { q.add(s.pop()); // restore queue original order } return true; } } for (int k = 0; k < size / 2; k++) { q.add(q.remove()); s.push(q.remove()); } for (int l = 0; l < size / 2; l++) s.push(q.remove()); while (!s.isempty()) q.add(s.pop()); } return true; }

if has hard time reading or can suggest way create less convoluted well, appreciate that. give thanks you, , sorry 1 time again bloated code.

why not utilize simple algorithm doesn't care if destroys queue in process, re-create queue first step?

public static boolean ispalindrome(queue<integer> q) { homecoming ispalindromedestructive(copyqueue(q)); } private static boolean ispalindromedestructive(queue<integer> q) { //destructive algorithm treats q disposable. } private static queue<integer> copyqueue(queue<integer> q) { homecoming new linkedlist<integer>(q); }

you can implement copyqueue want, works.

java stack queue palindrome

No comments:

Post a Comment