Created
September 14, 2019 18:05
-
-
Save wagfim/a8e4d8671114b10d6508840d51abaf74 to your computer and use it in GitHub Desktop.
Copy a stack to another using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
Stack newStack = new Stack(); | |
Stack clone = new Stack(); | |
//populate a stack | |
for (int i = 0; i < 10; i++) { | |
newStack.push(i); | |
} | |
//copy from one stack to another | |
copyStack(newStack, clone); | |
//show both stacks | |
System.out.print("Original stack: "); | |
showStack(newStack); | |
System.out.print("Clone stack: "); | |
showStack(clone); | |
} //end main() | |
public static void copyStack(Stack original, Stack destination) { | |
if (!original.isEmpty()) { | |
String temp = original.pop(); | |
copyStack(original, destination); | |
destination.push(Integer.parseInt(temp)); | |
original.push(Integer.parseInt(temp)); | |
} | |
} | |
public static void showStack(Stack stack) { | |
Stack clone = new Stack(); | |
copyStack(stack, clone); | |
System.out.print("["); | |
int stackSize = clone.getSize(); | |
for (int i = 0; i < stackSize - 1; i++) { | |
System.out.print(clone.pop() + ", "); | |
} | |
System.out.println(clone.pop() + "]"); | |
} | |
static class Stack { | |
private Node top; | |
private int size = 0; | |
public Node getTop() { | |
return top; | |
} | |
public void setTop(Node top) { | |
this.top = top; | |
} | |
public int getSize() { | |
return size; | |
} | |
boolean isEmpty() { | |
return top == null; | |
} | |
void push(int value) { | |
Node newNode = new Node(value); | |
if (isEmpty()) { | |
top = newNode; | |
size++; | |
} else { | |
newNode.setLastElement(top); | |
top = newNode; | |
size++; | |
} | |
} | |
//the return will have to be converted back to Integer before use | |
String pop() { | |
if (isEmpty()) { | |
return "empty"; | |
} else { | |
String temp = Integer.toString(top.getValue()); | |
top = top.getLastElement(); | |
size--; | |
return temp; | |
} | |
} | |
} //end Stack class | |
static class Node { | |
private int value; | |
private Node lastElement; | |
public Node(int value) { | |
this.value = value; | |
lastElement = null; | |
} | |
public int getValue() { | |
return value; | |
} | |
public Node getLastElement() { | |
return lastElement; | |
} | |
public void setLastElement(Node lastElement) { | |
this.lastElement = lastElement; | |
} | |
} //end Node class | |
} //end Main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment