public class Node<E> {
private E data;
private Node<E> next;
public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
public Node(E data) {
this(data, null);
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
public class Stack<E> {
protected Node<E> top;
protected int size;
public Stack() {
this.top = null;
this.size = 0;
}
public void push(E item) {
this.top = new Node<E>(item, top);
this.size++;
}
public E peek() {
if (this.top == null) {
throw new IllegalStateException("Can't peek() into empty stack.");
}
return this.top.getData();
}
public E pop() {
if (this.top == null) {
throw new IllegalStateException("Can't pop() from empty stack.");
}
E data = this.top.getData();
this.top = this.top.getNext();
this.size--;
return data;
}
public int size() {
return this.size;
}
}
public class PyramidStack<E extends Comparable<E>> extends Stack<E> {
@Override
public void push(E item) throws IllegalArgumentException {
if (top == null)
super.push(item);
if (top.getData().compareTo(item) > 0);
super.push(item);
}
@Override
public String toString() {
return toString();
}
public int countLessThan(E item) {
return 1;
}
public int compareTo(E item) {
if (((String)item).charAt(0) < ((String)top.getData()).charAt(0)) {
System.out.println(((String)item).charAt(0));
System.out.println(((String)top.getData()).charAt(0));
return 1;
}
else if (((String)item).charAt(0) == ((String)top.getData()).charAt(0)) {
System.out.println(((String)item).charAt(0));
System.out.println(((String)top.getData()).charAt(0));
return 1;
}
else
return -1;
}
}
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
String word;
System.out.println("This program will save some of the strings you enter.");
Stack<String> stack = new PyramidStack<String>();
do {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
word = scan.nextLine();
stack.push(word);
System.out.println(stack.peek());
} while (word.length() != 0);
}
}
Sorry a lot of code I know.

New Topic/Question
Reply



MultiQuote



|