Created
March 21, 2017 03:20
-
-
Save Bambina-zz/2a21c11ba9c1dfdbf84d7b70f46aa423 to your computer and use it in GitHub Desktop.
Stackの実装
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
import java.util.*; | |
import org.junit.*; | |
import static org.junit.Assert.*; | |
// Last In First Out | |
public class TestStack { | |
@Test | |
public void testStack(){ | |
Stack<Integer> stack = new Stack<Integer>(); | |
stack.push(1); | |
stack.push(2); | |
Integer obj = stack.peek(); | |
assertEquals("2", obj.toString()); | |
} | |
@Test | |
public void testStack2(){ | |
Stack<Integer> stack = new Stack<Integer>(); | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
stack.pop(); | |
assertEquals(2, stack.length()); | |
} | |
@Test | |
public void testStack3(){ | |
Stack<Integer> stack = new Stack<Integer>(); | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
Integer obj = stack.pop(); | |
assertEquals("3", obj.toString()); | |
} | |
} | |
class Stack<E> { | |
static class Node<E> { | |
public Node<E> next = null; | |
public E data; | |
} | |
Node<E> top; | |
void push(E e){ | |
Node<E> node = new Node<E>(); | |
node.data = e; | |
node.next = top; | |
top = node; | |
} | |
E peek(){ | |
return top.data; | |
} | |
E pop(){ | |
if(top != null){ | |
E obj = top.data; | |
top = top.next; | |
return obj; | |
} | |
return null; | |
} | |
int length(){ | |
if(top == null) { | |
return 0; | |
} | |
int length = 1; | |
Node<E> node = top; | |
while(node.next != null){ | |
node = node.next; | |
length++; | |
} | |
return length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment