1.3.5
当N为50时下面这段代码会打印什么?从较高的抽象层次描述给定正整数N时这段代码的行为。
Stack<Integer> stack = new Stack<Integer>();
while (N > 0){
stack.push(N % 2);
N = N / 2;
}
for (int d : stack) StdOut.print(d);StdOut.println();
解答:将一个数字每次除以二取余数,倒着排列后就是它的二进制数,如N = 50 的话就是110010,这里利用了栈,将入栈的余数倒叙输出了。
1.3.6
下面这段代码对q进行了什么操作?
Stack<String> stack = new Stack<>();
while(!q.isEmpty()){
//将队列按照先进先出的顺序 入栈
stack.push(q.dequeue);
}
while(!stack.isEmpty()){
//将栈内后进先出的元素 加入队列形成逆序
q.enqueue(stack.pop());
}
很明显,将队列中的元素,入栈出栈后,队列反转(逆序)了。
1.3.7
为Stack添加一个方法peek(),返回栈中最近添加的元素(而不弹出它)。
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* 用链表实现下压栈
*
* @author wangxinfu
*/
public class Stack<Item> implements Iterable<Item> {
private int size;
private Node first;
private class Node {
Item item;
Node next;
}
private class StackIterator implements Iterator<Item> {
//当前结点
Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException("Stack is Empty!");
}
Item item = current.item;
current = current.next;
return item;
}
}
/**
* 压栈 此处无需判断isEmpty()
* @param item
* @return
*/
public boolean push(Item item) {
//在头结点添加
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
size++;
return true;
}
public Item pop() {
if (isEmpty()) {
throw new NoSuchElementException("Stack is Empty");
}
//暂存item
Item item = first.item;
Node next = first.next;
first.item = null;
first.next = null;
first = next;
size--;
return item;
}
@Override
public Iterator<Item> iterator() {
return new StackIterator();
}
public int size() {
return size;
}
public boolean isEmpty() {
return first == null;
}
public Item peek(){
if (isEmpty()){throw new NoSuchElementException("Stack underflow");}
return first.item;
}
1.3.8
转载该篇博客解答 blog.csdn.net/furzoom/art…