110 likes | 220 Views
LIFO ( L ast I n F irst O ut). Stack. Operations on a Stack. pop. LIFO ( L ast I n F irst O ut). pop. peek. push. h. peek. push. g. push. e. d. push. f. b. empty. b. push. a. c. push. LIFO ( L ast I n F irst O ut). Stack. a. b. b. b. b. h. h. h. h. h.
E N D
LIFO (Last In First Out) Stack ITK 275
Operations on a Stack pop LIFO (Last In First Out) pop peek push h peek push g push e d push f b empty b push a c push ITK 275
LIFO (Last In First Out) Stack a b b b b h h h h h e e e e e e e e e f f f f f f f f f f f push push push pop push push push pop pop pop pop pop f e b b h b a a b h e f ITK 275
FIFO (Frst In First Out) Queue a b h e f ITK 275
ITKStack interface 1 publicinterface ITKStack<T> { T push(T obj); T peek(); T pop(); boolean empty(); } 2 2 6 3 1 4 4 3 5 5 6 ITK 275
publicclassLinkedListStack<T>implementsITKStack<T> { /*****Thisisaninnerclassforinternalnodes ********/ privatestatic class Node<E> { private E data; private Node<E> next; private Node(E data, Node<E> next) { // Construct a node pointing to next this.data = data; this.next = next; } } /****ThisistheendoftheinnerclassNode<E>******/ private Node<T> top; publicLinkedListStack() { top = null; } ..... ..... .... } Using an inner class for the internal nodes ITK 275
publicclassLinkedListStack<T>implementsITKStack<T>{ ..... ..... public T push(T obj){ top = new Node<T>(obj, top); return obj; } public T peek(){ returntop.data; } public T pop(){ T data = top.data; top = top.next; return data; } publicboolean empty(){ if (top == null) returntrue; returnfalse; } } Methods implementation ITK 275
a • ada • mom • eve • bob • deed • noon Palindromes • aaaaaaaaa • adada • mommom • eveeeeeeeeeeeve • bobdeedbob • abcdefghiihgfedcba ITK 275
publicstaticboolean isPalindrome(String aWord) { int j=aWord.length()-1; for (int i=0;i<aWord.length();i++) { if (! aWord.charAt(i).equals(aWord.charAt(j--)) returnfalse; } returntrue; }// end isPalindrome Palindrome Test ITK 275
Not random accessible a c d e d c a a c e e d c a Palindrome Test Using Stack fail ITK 275
publicstaticboolean isPalindrome(String aWord) { ArrayList<Character> cstr = new ArrayList<Character>(); LinkedListStack<Character> rcstr = new LinkedListStack<Character>(); for (int i=0;i<aWord.length();i++) { cstr.add(aWord.charAt(i)); rcstr.push(aWord.charAt(i)); } for (int i=0;i<aWord.length();i++) if (! rcstr.pop().equals( cstr.get(i) )) returnfalse; returntrue; }// end isPalindrome Palindrome test ITK 275