Data Structure
[Data Structure] Java μ€ν(Stack) μ¬μ©
An effort will never betray π
2021. 1. 15. 13:53
λ°μν
- μ΄ κΈμ "μ¨λΌμΈ μλ° μ€ν°λ λ΄μ©"μ μ 리ν κΈμ λλ€.
Stackμ΄λ?
μ€νμ μ± μ μλ κ²μ²λΌ λ°μ΄ν°λ₯Ό λ΄μ μ μλ μλ£κ΅¬μ‘° μ λλ€.
μ€νμ κ°μ₯ ν° νΉμ§μ First In Last Out (FILO) ꡬ쑰λ₯Ό κ°μ§κ³ μμ΅λλ€.
λ°°μ΄λ‘ μ€ν ꡬν
public class Stack {
final int MAX_SIZE = 100;
int arr[];
int size;
public Stack(){
arr = new int[MAX_SIZE];
size = 0;
}
public void push(int data){
if(size<MAX_SIZE){
arr[size++] = data;
}
}
public int pop(){
if(size>0){
size--;
return 1;
}
return 0;
}
public int top(){
if(size>0){
return arr[size-1];
}
return -1;
}
public boolean isFull(){
if(size == MAX_SIZE){
return true;
}
return false;
}
}
public class Main {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.top()); // 3
stack.pop();
System.out.println(stack.top()); // 2
stack.pop();
System.out.println(stack.top()); // 1
stack.pop();
}
}
λ Έλλ‘ μ€ν ꡬν
public class ListNode {
int data;
ListNode next;
public ListNode(int data) {
this.data = data;
next = null;
}
}
λ€μ ν΄λμ€λ λ Έλλ₯Ό ꡬννλ μ½λμ λλ€.
public class ListNodeStack {
ListNode head;
int size;
public ListNodeStack() {
head = null;
size = 0;
}
void push(int data){
ListNode node = head;
if(size == 0){
node = new ListNode(data);
head = node;
}
else{
while(node.next != null){
node = node.next;
}
node.next = new ListNode(data);
}
size++;
}
int pop(){
ListNode node = head;
int data;
if(size == 1){
data = node.data;
node = null;
head = node;
}
else{
while(node.next.next!=null){
node = node.next;
}
data = node.next.data;
node.next = null;
}
size--;
return data;
}
public int getSize() {
return size;
}
}
public class Main {
public static void main(String[] args) {
ListNodeStack stack = new ListNodeStack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.getSize()); // 3
System.out.println(stack.pop()); // 3
System.out.println(stack.pop()); // 2
System.out.println(stack.pop()); // 1
}
}
λ°μν