算法1.2下压堆栈(链表表示)API
public class Stack<Item> implements Iterable<Item> | ||||||
private Node first 栈顶(最近添加的元素) private int N 元素数量
| ||||||
public boolean isEmpty() public int size() public void push(Item item) 头插法,入栈 public Item pop() 删除首节点,出栈 @Override public Iterator<Item> iterator() 返回一个迭代器 |
头插法,入栈
删除首节点,出栈(出队)
package _1_3linkedList;
import java.util.Iterator;
/*算法1.2下压堆栈(链表表示)
*/
public class Stack<Item> implements Iterable<Item>
{
private Node first; /*the top of the stack,recently added elements*/
private int N; /*Number of elements*/
public class Node /*定义了节点的嵌套类*/
{
Item item;
Node next;
}
public boolean isEmpty()
{
return N==0; /*or first==null*/
}
public int size()
{
return N;
}
public void push(Item item)
{ /*头插法,入栈*/
Node oldfirst=first;
first=new Node();
first.item=item;
first.next=oldfirst;
N++;
}
public Item pop()
{ /*删除首节点,出栈*/
Item item=first.item;
first=first.next;
N--;
return item;
}
@Override
public Iterator<Item> iterator()
{
return new ListIterator();
}
private class ListIterator implements Iterator<Item> /*迭代器*/
{
private Node current=first;
@Override
public boolean hasNext()
{
return current!=null;
}
@Override
public Item next()
{
Item item=current.item;
current=current.next;
return item;
}
}
}
测试用例:
package _1_3linkedList;
import java.util.Scanner;
/*算法1.2下压堆栈(链表表示)-测试用例
*/
public class TestStack
{
public static void main(String[] args)
{
Stack<String> stack=new Stack<String>();
Scanner sc=new Scanner(System.in);
while(true)
{
String s=sc.nextLine();
if(s.equals("eof"))
break;
if(!s.equals("-"))
stack.push(s);
else if(!stack.isEmpty())
System.out.println(stack.pop());
}
for(String s:stack)
System.out.println(s);
sc.close();
}
}
输入:
1
2
3
4
5
-
5
-
4
6
eof
6
3
2
1