본문 바로가기

한화시스템 BEYOND SW캠프/TIL

[6주차] 24.02.15 목요일

자료구조

 

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/*
    싱글 쓰레드 : 순차실행 main start - 파일 다운로드(A) - 파일 다운로드(B) - 파일 다운로드(C) - main end
    멀티 쓰레드 : 병렬실행 main start - 파일 다운로드(A)(thread) - 파일 다운로드(B)(thread) - 파일 다운로드(C)(thread) - main end
    ArrayList - Vector

    Vector : 강제 동기화로 인해서 성능에 문제가 생긴다.
 */

public class VectorDemoMain {
    public static void main(String[] args) {
//        case01
        List<Integer> lst = new ArrayList();
        List<Integer> vec = new Vector();

        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                lst.add(1); // not synchronized
                vec.add(1); // synchronized
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                lst.add(1); // not synchronized
                vec.add(1); // synchronized
            }
        }).start();

        // 출력을 위한 쓰레드
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("ArrayList size = " + lst.size());
                System.out.println("Vector size = " + vec.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        List<Integer> vec2 = new Vector();

        // 두 개의 쓰레드가 동일한 Vector에 접근하는 코드
        // 인스턴스 자체는 동기화가 되어있지 않기 때문이다.
        new Thread(() -> {
            vec2.add(1);
            vec2.add(2);
            vec2.add(3);
            System.out.println(vec2.get(0));
            System.out.println(vec2.get(1));
            System.out.println(vec2.get(2));
        }).start();

        new Thread(() -> {
            vec2.remove(0);
            vec2.remove(0);
            vec2.remove(0);
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("Vector size = " + vec2.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

 

import com.encore.data.structure.list.EncoreNodeList;

import java.io.*;

public class LinkedListDemoMain {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("데이터를 입력하세요 : ");
        int data = Integer.parseInt(br.readLine());

        // LinkedList 의 헤더를 생성
        EncoreNodeList mgr = new EncoreNodeList(data);
        while (true) {
            System.out.println("메뉴를 선택하세요 ");
            System.out.println("1. 연결리스트 데이터 출력 ");
            System.out.println("2. 연결리스트 데이터 추가 ");
            System.out.println("3. 연결리스트 데이터 삭제 ");
            System.out.println("99. 프로그램 종료 ");
            System.out.print("원하시는 번호를 입력 : ");
            int number = Integer.parseInt(br.readLine());
            switch (number) {
                case 1:
                    System.out.println(">>> LinkedList 데이터 출력 <<<");
                    mgr.desc();
                    break;
                case 2:
                    System.out.println(">>> LinkedList 데이터 추가 <<<");
                    int add_data = Integer.parseInt(br.readLine());
                    mgr.add(add_data);
                    break;
                case 3:
                    System.out.println(">>> LinkedList 데이터 삭제 <<<");
                    // 삭제할 데이터 입력
                    int remove_data = Integer.parseInt(br.readLine());
                    System.out.println(mgr.remove(remove_data) ? "삭제 완료" : "삭제 실패");
                    break;
                default:
                    System.exit(0);
            }
        }
    }
}

 

package com.encore.data.structure.list;

public class EncoreNode {
    private int data;
    private EncoreNode node;

    public EncoreNode(int data) {
        this.data = data;
    }

    public int getData() {
        return this.data;
    }

    public void setNode(EncoreNode node) {
        this.node = node;
    }

    public EncoreNode getNode() {
        return this.node;
    }
}

 

package com.encore.data.structure.list;

public class EncoreNodeList {
    private EncoreNode head;

    public EncoreNodeList(int data) {
        this.head = new EncoreNode(data);
    }

    public void add(int data) {
        if (this.head == null) {
            // 연결 리스트의 헤더가 생성되지 않은 상태
            this.head = new EncoreNode(data);
        } else {
            // 연결되어지는 노드를 생성
            EncoreNode node = this.head;
            while (node.getNode() != null) {
                node = node.getNode();
            }
            node.setNode(new EncoreNode(data));
        }
    }

    public boolean remove(int remove_data) {
        // 데이터가 하나이고 삭제하고자 하는 데이터가 head인 경우
        if (this.head.getData() == remove_data) {
            EncoreNode temp = this.head;
            this.head = this.head.getNode();
            temp = null;
        } else {
            // 삭제해야할 데이터가 head가 아닌 중간 또는 마지막 노드인 경우
            EncoreNode node = this.head;

            while (node.getNode() != null) {
                if (node.getNode().getData() == remove_data) {
                    EncoreNode temp = node.getNode();
                    node.setNode(node.getNode().getNode());
                    temp = null;
                    return true;
                } else {
                    node = node.getNode();
                }
            }
        }
        
        return false;
    }

    public void desc() {
        EncoreNode node = this.head;
        while (node != null) {
            System.out.println("debug >>>> " + node.getData());
            node = node.getNode();
        }
    }
}

 

import com.encore.data.structure.stack.EncoreStack;

import java.util.Stack;

public class StackDemoMain {
    public static void main(String[] args) {
//        Stack<Integer> stack = new Stack<Integer>();
//        stack.push(10);
//        stack.push(20);
//        stack.push(30);
//        stack.add(40);
//        System.out.println(stack);
//        System.out.println(stack.pop());
//        System.out.println(stack);
//        System.out.println(stack.pop());
//        System.out.println(stack);
//        System.out.println(stack.pop());
//        System.out.println(stack);
//        System.out.println(stack.pop());
//        System.out.println(stack);
//        System.out.println(stack.pop());

//        Stack<String> stack = new Stack<>();
//        System.out.println("empty : " + stack.empty());
//        System.out.println("empty : " + stack.isEmpty());
//        System.out.println("스택에 데이터가 없을 때 입력하고 싶다면?");
//        if (stack.isEmpty()) {
//            stack.push("One");
//            stack.push("Two");
//            stack.push("Three");
//        }
//
//        System.out.println(stack);
//        stack.add(0, "Four");
//        System.out.println(stack);
//        String str = stack.pop();
//        System.out.println("pop : " + str);
//        System.out.println(str.equals("Four"));
//        System.out.println("size : " + stack.size());
//        System.out.println(stack);
//        System.out.println("search : " + stack.search("One"));
//        System.out.println("search : " + stack.search("Four"));

        EncoreStack stack = new EncoreStack();
//        stack.push(10);
//        System.out.println(stack.pop());

        stack.push(10);
        stack.push(9);
        stack.push(8);
        stack.push(7);

        if (stack.isEmpty()) {
            System.out.println("스택이 비어있습니다.");
        } else {
            System.out.println(stack.pop());
        }

        stack.prtStack();
        System.out.println("peek : " + stack.peek());
        stack.prtStack();

        System.out.println("main end");
    }
}

 

package com.encore.data.structure.stack;

import java.util.EmptyStackException;

public class EncoreStack {
    private int[] stackArr;
    private int top;

    public EncoreStack() {
        stackArr = new int[6];
        top = -1;
    }

    public void push(int data) {
        stackArr[++top] = data;
    }

    public int pop() {
        if (top == -1) {
            throw new ArrayIndexOutOfBoundsException();
        }
        return stackArr[top--];
    }

    public boolean isEmpty() {
        if (top == -1) {
            return true;
        } else {
            return false;
        }
    }

    // 마지막 인덱스값을 리턴
    public int peek() {
        if (top == -1) {
            throw new EmptyStackException();
        }
        return stackArr[top];
    }

    // 스택에 들어있는 요소 출력
    public void prtStack() {
        for (int i = top; i >= 0; --i) {
            System.out.println(stackArr[i]);
        }
    }
}

 

import java.util.LinkedList;
import java.util.Queue;

/*
    먼저 들어간 데이터가 먼저 나오는 FIFO(Enqueue, Dequeue)
 */
 
public class QueueDemoMain {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(10);
        queue.offer(20);
        queue.offer(30);
        queue.offer(40);

        System.out.println("peek : " + queue.peek());
        System.out.println("poll : " + queue.poll());
        System.out.println("size : " + queue.size());
        System.out.println("remove : " + queue.remove());
        System.out.println("size : " + queue.size());
        System.out.println("clear : ");
        queue.clear();
        System.out.println("size : " + queue.size());

        System.out.println("main end");
    }
}

'한화시스템 BEYOND SW캠프 > TIL' 카테고리의 다른 글

[8주차] 24.02.27 화요일  (0) 2024.02.27
[8주차] 24.02.26 월요일  (1) 2024.02.26
[6주차] 24.02.14 수요일  (0) 2024.02.14
[6주차] 24.02.13 화요일  (0) 2024.02.13
[5주차] 24.02.08 목요일  (0) 2024.02.08