-
[whiteship스터디 4주차 과제]ListNode클래스를 이용해 Stack구현CS/자료구조 2021. 5. 16. 10:39
과제 4. 앞서 만든 ListNode를 사용해서 Stack을 구현하세요.
- ListNode head를 가지고 있는 ListNodeStack 클래스를 구현하세요.
- void push(int data)를 구현하세요.
- int pop()을 구현하세요.
package Week4_Stack_ListNode; public class ListNode { public int data; public ListNode next; ListNode(){ this.data = 0; this.next=null; } }
package Week4_Stack_ListNode; public class Stack { public ListNode head; public int size = 0; public void push(int data) { ListNode node = new ListNode(); node.data = data; if (head == null) { head = node; size = 1; return; } ListNode temp = head; for (int i = 1; i < size; i++) { temp = temp.next; } temp.next = node; size++; } public int pop() { if (head == null || size == 0) { System.out.println("스택이 비어있습니다."); return -1; } ListNode temp = head; for (int i = 1; i < size; i++) { temp = temp.next; } int data = temp.data; size--; temp = null; return data; } public void stackList() { if (head == null || size == 0) { System.out.println("스택이 비어있습니다."); return; } ListNode temp = head; for (int i = 0; i < size; i++) { System.out.print("|"); System.out.print(temp.data); temp = temp.next; } System.out.println("|"); } public int getSize() { return this.size; } }
package Week4_Stack_ListNode; public class Test { public static void main(String[] args) { Stack stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println("스택 리스트 출력"); stack.stackList(); System.out.println("Pop Item = " + stack.pop()); System.out.println("Pop Item = " + stack.pop()); System.out.println("Pop Item = " + stack.pop()); System.out.println("Pop Item = " + stack.pop()); System.out.println(stack.pop()); System.out.println(stack.size); } }
'CS > 자료구조' 카테고리의 다른 글
Swift에서 힙, 우선순위 큐 사용하기 (100% 순수 구현을 곁들인) (0) 2024.07.30 [whiteship스터디 4주차 과제]LinkedList를 이용해 Queue 구현 (0) 2021.06.19 [whiteship스터디 4주차 과제]배열을 이용한 스택 구현 (0) 2021.05.15 [whiteship스터디]single linked list 구현 (0) 2021.04.11