반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 구현
- red-black tree
- qsort
- 총정리
- function_template
- '0'
- sort
- list
- deletion
- STL
- 자료구조
- 알고리즘
- c++
- Algorithm
- 예제
- Heap
- Critical_Path_Analysis
- 13305
- singly Linked List
- 문법
- template
- 백준
- Pair
- class_template
- Articulation_Point
- connected_component
- sstream
- 5397
- data_structure
- Biconnected_Component
Archives
- Today
- Total
- Today
- Total
- 방명록
어제의 나보다 성장한 오늘의 나
[java] Stack 클래스 사용법 및 예제 총정리 본문
반응형
자바 언어를 좀 더 단단히 배우고 싶어서 자바 자료 구조에 대해서 정리하면서 공부해 보려고 한다.
오늘은 Stack에 대해서 정리를 해보려고 한다.
0) 선언
Stack<자료형 타입> stk = new Stack<>();
예시
Stack<Integer> stk = new Stack<>();
Stack<String> stk2 = new Stack<>();
1) 스택에 값 추가 ( add , push 함수 )
stk.add(10);
stk.push(20);
두 가지 방법이 있다.
차이점은 반환 값이 add는 true / false , push는 집어 넣은 값이 리턴 된다.
System.out.println(stk.add(30)); // true 출력
System.out.println(stk.push(40)); // 40 출력
2) 스택에 값 제거 ( pop 함수 )
pop된 값을 출력 한다.
stk.pop();
System.out.println(stk.pop()); // 반환 값 출력
스택 비었는 지 확인 ( empty 함수 )
boolean isempty = stk.empty();
3) isempty , push , pop 사용 예제
public class stack {
public static void main(String[] args) {
Stack<Integer> stk = new Stack<>();
stk.add(10); // 10
stk.push(20); // 20 10
stk.push(30); // 30 20 10
while(!stk.empty()){
System.out.println(stk.pop());
}
}
}
출력
30
20
10
4) 최 상단 노드 확인 ( peak 함수 )
최상단 노드 반환
stk.peak();
5) 노드의 갯수 ( size 함수 )
노드의 갯수 반환
stk.size();
6) 특정 노드를 가지고 있는 지 확인 ( contain 함수 )
stk.contain(value);
peak , size , contain 사용 예제
public class stack {
public static void main(String[] args) {
Stack<Integer> stk = new Stack<>();
stk.push(10);
stk.push(20);
stk.push(30);
System.out.println(stk.peek());
System.out.println(stk.size());
System.out.println(stk.contains(30));
System.out.println(stk.contains(40));
}
}
출력
30
3
true
false
7) stack 속 모든 값 삭제 ( clear 함수 )
stk.clear();
8) 차례로 출력 ( for문 사용 )
자료형 타입을 맞춰 주고 임의의변수 : 스택이름
stk.push(10);
stk.push(20);
stk.push(30);
for(Integer s : stk) {
System.out.println(s);
}
출력
10
20
30
9) 특정 노드 위치 반환 ( search 함수 )
stk.search(value);
stk.push(10);
stk.push(20);
stk.push(30);
System.out.println(stk.search(10));
System.out.println(stk.search(20));
System.out.println(stk.search(30));
출력
3
2
1
10) 스택 정렬
stk.sort(null); // 오름차순
stk.sort(Collections.reverseOrder()); // 내림차순
stk.push(30);
stk.push(10);
stk.push(20);
stk.sort(null);
for(Integer s : stk) {
System.out.println(s);
}
출력
10
20
30
반응형
'java' 카테고리의 다른 글
[ Mac OS / Java ] 맥북 자바 버전 변경 (1) | 2022.12.26 |
---|---|
[java] HashMap 사용법 및 예제 총정리 (0) | 2022.12.19 |
Comments