How do I copy a stack in Java?

前端 未结 6 651
星月不相逢
星月不相逢 2020-12-03 21:03

I have a stack A and I want to create a stack B that is identical to stack A. I don\'t want stack B to simply be a pointer to A -- I actually want to create a new stack B th

6条回答
  •  遥遥无期
    2020-12-03 21:27

     /**
         * Copy constructor for the Stack class
         * @param original the Stack to copy
         * @postcondition a new Stack object which is
         * an identical, but distinct, copy of original
         */
        public Stack(Stack original) {
            if (original.length == 0)
            {
                length = 0;
                top = null;
            } else
            {
                Node temp = original.top;
                while (temp != null)
                {
                    push(temp.data); // inserts into this
                    temp = temp.next;
                }
                temp = top;
                temp = temp.next;
                top.next = null;
                while (temp != null){
                    push(temp.data); // inserts into this
                    temp = temp.next;
                }
    
            }
        }
    

提交回复
热议问题