question:
Copy a stack. Create a new constructor for the linked-list implementatiion of Stack so that
Stack<Item> t = new Stack<Item>(s);
makes t a reference to a new and independent copy of stack s.
answer:
//借用一个中转栈temp来进行复制
import edu.princeton.cs.algs4.*; public class CopyStack<Item> { private class Node { Item item; Node next; } private Node top; private int N; public CopyStack() { top = null; N = 0; } public CopyStack(CopyStack<Item> stack) { CopyStack<Item> temp = new CopyStack<Item>();//主要是用这个temp转换一下 while(!stack.isEmpty()) { Item item = stack.pop(); temp.push(item); } while(!temp.isEmpty()) { Item item = temp.pop(); this.push(item); stack.push(item); } } public boolean isEmpty() { return N == 0; } public void push(Item item) { Node node = new Node(); node.item = item; node.next = null; if(N == 0) { top = node; N++; return; } N++; node.next = top; top = node; } public Item pop() { if(N == 0) { return null; } N--; Item item = top.item; top = top.next; return item; } public static void main(String[] args) { CopyStack<String> s1 = new CopyStack<String>(); s1.push("c"); s1.push("j"); s1.push("w"); CopyStack<String> s2 = new CopyStack<String>(s1); for(int i = 0; i < 3; i++) { StdOut.print("s1\t" + s1.pop() + "\ts2\t" + s2.pop() + "\n"); } } }