# 算法－第四版－练习1.3.2解答

it was - the best - of times - - - it was - the - -

Stack：

/**
* Description :
* Author      : mn@furzoom.com
* Date        : Sep 27, 2016 5:07:34 PM
*/
package com.furzoom.lab.algs.ch103;

import java.util.Iterator;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

/**
* ClassName    : Stack <br>
* Function     : TODO ADD FUNCTION. <br>
* date         : Sep 27, 2016 5:07:34 PM <br>
*
* @version
*/
public class Stack<Item> implements Iterable<Item>
{
private Node first;
private int n;
private class Node
{
Item item;
Node next;
}

public boolean isEmpty()
{
return 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 ReverseArrayIterator();
}

private class ReverseArrayIterator implements Iterator<Item>
{
private Node p = first;
@Override
public boolean hasNext()
{
return p != null;
}

@Override
public Item next()
{
Item item = p.item;
p = p.next;
return item;
}

}

public static void main(String[] args)
{
Stack<String> s;
s = new Stack<String>();
while (!StdIn.isEmpty())
{
if (!item.equals("-"))
s.push(item);
else if (!s.isEmpty())
StdOut.print(s.pop() + " ");
}
StdOut.println("(" + s.size() + " left on stack)");
}
}


E10302.txt

it was - the best - of times - - - it was - the - -

>java -cp ".;../lib/algs4.jar" com
.furzoom.lab.algs.ch103.Stack < com/furzoom/lab/algs/ch103/E10302.txt
was best times of the was the it (1 left on stack)

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客