Skip to content

Instantly share code, notes, and snippets.

@Bambina-zz
Last active April 20, 2017 14:19
Show Gist options
  • Save Bambina-zz/460b636a313fec9600360dd5007150fb to your computer and use it in GitHub Desktop.
Save Bambina-zz/460b636a313fec9600360dd5007150fb to your computer and use it in GitHub Desktop.
3.2 pushとpopに加えて、最小の要素を返す関数minを持つスタックをどのようにデザインしますか?ただしpush、pop、min関数はすべてO(1)の実行時間になるようにしてください。
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class StackTest {
@Test
public void testStack(){
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
assertEquals("3", String.valueOf(s.pop()));
}
@Test
public void testStackReturnsMinValue(){
Stack s = new Stack();
s.push(3);
assertEquals(3, s.min());
s.push(2);
assertEquals(2, s.min());
s.push(1);
assertEquals(1, s.min());
s.pop();
assertEquals(2, s.min());
s.pop();
assertEquals(3, s.min());
s.push(1);
assertEquals(1, s.min());
s.push(2);
assertEquals(1, s.min());
s.push(3);
assertEquals(1, s.min());
s.pop();
assertEquals(1, s.min());
s.pop();
assertEquals(1, s.min());
}
@Test
public void testCounter(){
Stack s = new Stack();
s.push(1);
assertEquals(1, s.count());
}
@Test
public void testCounter2(){
Stack s = new Stack();
s.push(1);
s.pop();
assertEquals(0, s.count());
}
}
class Stack {
class Node {
public Integer value = null;
public Node next = null;
}
public Node minHead;
public Node minTail;
public Node head;
public Node tail;
public Stack(){
this.minHead = new Node();
this.minTail = new Node();
this.head = new Node();
this.tail = new Node();
this.minHead.next = this.minTail;
this.head.next = this.tail;
}
public void push(Integer val){
Node node = new Node();
node.value = val;
node.next = this.head.next;
this.head.next = node;
if(this.minHead.next != this.minTail){
if(this.minHead.next.value > val){
Node min = new Node();
min.value = val;
min.next = this.minHead.next;
this.minHead.next = min;
}
} else {
Node min = new Node();
min.value = val;
this.minHead.next = min;
min.next = this.minTail;
}
}
public Integer pop(){
if(this.head.next == this.tail){
return null;
} else {
Node node = this.head.next;
this.head.next = node.next;
if(node.value == this.minHead.next.value){
this.minHead.next = this.minHead.next.next;
}
return node.value;
}
}
public int min(){
return this.minHead.next.value;
}
public int count(){
int counter = 0;
Node node = this.head;
while(node.next != tail){
node = node.next;
counter++;
}
return counter;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment