1:先进后出栈的实现:
才用头结点的方式:
package com.algorithm.common;
import java.util.Iterator;
/**
* 链表实现先进后出的Stack
* @author lijunqing
*/
public class Stack<Item> implements Iterable<Item> {
private int N;
private Node head;
class Node {
private Item item;
private Node next;
}
public Stack() {
N=0;
head=new Node();
}
/**
* 入栈
* @param item head---first ---head.next
*/
public void push(Item item) {
Node first=new Node();
first.item=item;
first.next=head.next;
head.next=first;
N++;
}
/**
* 出栈 head --- head.next.next
* @return
*/
public Item pop() {
Node first=head.next;
head.next=first.next;
N--;
return first.item;
}
public int size() {
return N;
}
public boolean isEmpty() {
if(N == 0) {
return true;
}
return false;
}
@Override
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current=head.next;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
Item item=current.item;
current=current.next;
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public static void main(String[] args) {
Stack<String> s=new Stack<String>();
s.push("as");
s.push("bs");
s.push("eee");
// System.out.println(s.size());
// String a=s.pop();
// String b=s.pop();
// System.out.println(a + " 2 " + b);
// System.out.println(s.isEmpty());
Iterator<String> iterator=s.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
结果:
eee
bs
as