链表实现栈-Java
package MyStack;
public class MyStackLinked<AnyType> {
private int theSize;
private Node<AnyType> head;
private Node<AnyType> tail;
public MyStackLinked() {}
private static class Node<AnyType> {
private AnyType data;
private Node<AnyType> next;
public Node(AnyType x, Node<AnyType> n) {
data = x;
next = n;
}
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return theSize == 0;
}
public void push(AnyType data) {
Node<AnyType> newNode = new Node<AnyType>(data, null);
if (size() == 0) {
head = newNode;
tail = newNode;
theSize++;
} else {
newNode.next = head;
head = newNode;
theSize++;
}
}
public AnyType pop() {
if (size() == 0) {
throw new IndexOutOfBoundsException("empty");
}
AnyType item = head.data;
head = head.next;
theSize--;
return item;
}
public AnyType top() {
if (size() == 0) {
throw new IndexOutOfBoundsException("empty");
}
return head.data;
}
}
测试
package MyLinkedList;
public class MyLinkedListTest {
public static void main(String[] args) {
MyLinkedList<String> mll = new MyLinkedList<String>();
mll.add("a");
mll.add("b");
mll.add("c");
for (String s : mll) {
System.out.println(s);
}
mll.set(2, "cc");
String str = mll.get(2);
System.out.println(str);
System.out.println(mll.size());
System.out.println(mll.isEmpty());
mll.remove(1);
for (String s : mll) {
System.out.println(s);
}
System.out.println("clear");
mll.clear();
for (String s : mll) {
System.out.println(s);
}
}
}