-
[Data Structure] Java ์คํ(Stack) ์ฌ์ฉData Structure 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 } }
๋ฐ์ํ'Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Data Structure] Java ์ด์งํธ๋ฆฌ(Binary Tree) ๊ตฌํ (0) 2021.01.17 [Data Structure] Java ํ(Queue) ์ฌ์ฉ (0) 2021.01.15 [Data Structure] Java ๋งํฌ๋ ๋ฆฌ์คํธ(LinkedList) ๊ตฌํ (0) 2021.01.15 [Data Structure] multimap ์ฌ์ฉ๋ฒ (0) 2020.11.08 [Data Structure] Set ์ฌ์ฉ๋ฒ (0) 2020.03.19