



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The concept of stacks as a linear data abstraction, their implementation using vector and linkedlist, and various applications such as parentheses checking, towers of hanoi, and searching/backtracking. The document also discusses the use of stacks in recursive algorithms and visualization.
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!




Stack Applications: Parentheses Checking
// Import statements. public class ParenCheck { private Stack stk = new Vector();
private void push(char c) { stk.addLast(new Character(c)); } private void check(char c) { // Check stack for balanced parentheses. if (stk.isEmpty()) reportError(); // Didn’t balance! Character s = (Character)stk.getLast(); // Get character on stack stk.removeLast(); // and remove it! if (c != s.charValue()) reportError(); // If not same Æ error! }
public static void main(String [] args) { try { ParenCheck world = new ParenCheck(System.in); } catch (IOException e) { System.out.println(“Received IO Exception “ + e); } } ...
Stack Applications: Parentheses Checking
public ParenCheck(InputStream in) throws IOException { int i = in.read(); while (i != -1) { if (i == ‘(‘ ) push (‘)’); else if (i == ‘{‘ ) push (‘}’); else if (i == ‘[‘ ) push (‘]’); else if (i == ‘)’ ) check(‘)’); else if (i == ‘}’ ) check(‘}’); else if (i == ‘]’ ) check(‘]’); i = i.read(); } if (stk.isEmpty()) System.out.println(“Parenthesis Balance”); else reportError(); } } // End of class ParenCheck.
Stack Applications: Towers of Hanoi
Place 8 queens on a chessboard so that none can capture
another (no two in the same row, column, or diagonal) :
Stack Applications: 8 Queens
a b c d e f g h
Place 8 queens on a chessboard so that none can capture
another (no two in the same row, column, or diagonal) :
Stack Applications: 8 Queens
a b c d e f g h
Place 8 queens on a chessboard so that none can capture
another (no two in the same row, column, or diagonal) :
Stack Applications: 8 Queens
a b c d e f g h
Place 8 queens on a chessboard so that none can capture
another (no two in the same row, column, or diagonal) :
Stack Applications: 8 Queens
a b c d e f g h
Place 8 queens on a chessboard so that none can capture
another (no two in the same row, column, or diagonal) :
Stack Applications: 8 Queens
a b c d e f g h
you may have to backup all the way to the first row)
Stack Applications: Knight’s Tour
Can a knight visit each square on the chessboard exactly
once (using only legal chess moves) :