ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [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);
        }
    }
    

     

Designed by Tistory.