Java Reference
In-Depth Information
top = top.next;
return hold;
} //end pop
} //end class Stack
If we need to work with a stack of characters, we just need to change the NodeData class to the following:
public class NodeData {
char ch;
public NodeData(char c) {
ch = c;
}
public char getData() {return ch;}
public static NodeData getRogueValue() {return new NodeData('$');}
public int compareTo(NodeData nd) {
if (this.ch == nd.ch) return 0;
if (this.ch < nd.ch) return -1;
return 1;
}
public String toString() {
return ch + "";
}
} //end class NodeData
4.3.1 Example: Convert from Decimal to Binary
Consider the problem of converting a positive integer from decimal to binary. We can use an integer stack, S , to do this
using repeated division by 2 and saving the remainders. Here is the algorithm:
initialize S to empty
read the number, n
while (n > 0) {
push n % 2 onto S
n = n / 2
}
while (S is not empty) print pop(S)
This algorithm is implemented in Program P4.4. Only the class DecimalToBinary is shown. The classes NodeData ,
Node , and Stack are the same as in Program P4.3.
Program P4.4
import java.util.*;
public class DecimalToBinary {
 
Search WWH ::




Custom Search