package datastruct;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* 用单链表实现栈,头插法
* @author Wee bing
* @param <Item>
*/
public class MyStack<Item> implements Iterable<Item> {
private Node<Item> head;//头节点
private int n;//元素个数
@SuppressWarnings("hiding")
private class Node<Item> {
private Item item;
private Node<Item> next;
private Node(Item item) {
this.item = item;
}
}
public MyStack() {
head = null;
}
//栈中元素的个数
public int size() {
return n;
}
//栈是否为空
public boolean isEmpty() {
return n == 0;
}
//入栈
public void push(Item item) {
if (item == null) throw new NullPointerException();
Node<Item> oldHead = head;
head = new Node<Item>(item);
head.next = oldHead;
n++;
}
//偷瞄栈顶元素
public Item peek() {
if (isEmpty()) throw new NoSuchElementException();
return head.item;
}
//出栈
public Item pop() {
if (isEmpty()) throw new NullPointerException();
Item item = head.item;
head = head.next;
n--;
return item;
}
//元素迭代
@Override
public Iterator<Item> iterator() {
// TODO Auto-generated method stub
return new MyIterator<Item>(head);
}
@SuppressWarnings("hiding")
private class MyIterator<Item> implements Iterator<Item> {
private Node<Item> cur;
private MyIterator(Node<Item> head) {
this.cur = head;
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return cur != null;
}
public Item next() {
Item item = cur.item;
cur = cur.next;
return item;
}
}
//测试
public static void main(String[] args) {
MyStack<Integer> ms = new MyStack<Integer>();
ms.push(8);
ms.push(5);
ms.push(11);
ms.push(100);
ms.push(50);
ms.push(70);
ms.push(77);
ms.push(200);
System.out.println(ms.size());
System.out.println(ms.pop());
System.out.println(ms.size());
System.out.println(ms.pop());
System.out.println(ms.size());
System.out.println("--------------------------");
Iterator<Integer> arr = ms.iterator();
while (arr.hasNext()) {
System.out.println(arr.next());
}
System.out.println(ms.size());
System.out.println(ms.peek());
}
}
367



被折叠的 条评论
为什么被折叠?



