Stack & Queue
Stack & Queue
Stack
import java.util.EmptyStackException; public class StackArray { int top; int size; int[] stack; public StackArray(int size) { this.size = size; stack = new int[size]; top = -1; } public void push(int item) { if (top >= size) { throw new StackOverflowError(); } stack[top++] = item; } public int pop() { if (top == 0) { throw new EmptyStackException(); } int data = stack[top]; stack[top--] = 0; return data; } public int search(int target) { for (int i = 0; i < top; i++) { if (stack[i] == target) { return i; } } return -1; } }import java.util.EmptyStackException; public class StackLinked { public static void main(String[] args) { StackLinked stack = new StackLinked(); for (int i = 0; i < 10; i++) { stack.push(i); } stack.display(); // 9-> 8-> 7-> 6-> 5-> 4-> 3-> 2-> 1-> 0-> System.out.println(stack.pop()); // 9 stack.display(); // 8-> 7-> 6-> 5-> 4-> 3-> 2-> 1-> 0-> } private Node top; public StackLinked() { top = null; } public boolean isEmpty() { return top == null; } public void push(int item) { Node node = new Node(item); node.next = top; // 연결 top = node; // top은 Stack의 가장 최근에 들어온 데이터를 가리킨다. } public int pop() { if (top == null) { throw new EmptyStackException(); } Node node = top; top = top.next; return node.item; } public int search(int target) { int id = 0; Node temp = top; while (temp != null) { if (temp.item == target) { return id; } temp = temp.next; id++; } return -1; } public void display() { if (top == null) { throw new EmptyStackException(); } Node temp = top; while (temp != null) { System.out.print(temp.item + "-> "); temp = temp.next; } System.out.println(); } public class Node { private int item; private Node next; public Node(int item) { this.item = item; next = null; } } }
Queue
Deque
Last updated