JAVA实现栈

来源:互联网 发布:js获取系统时间 编辑:程序博客网 时间:2024/06/04 23:30


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;}//元素迭代@Overridepublic Iterator<Item> iterator() {// TODO Auto-generated method stubreturn 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;}@Overridepublic boolean hasNext() {// TODO Auto-generated method stubreturn 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());}}




1 0
原创粉丝点击