연결리스트 - 백준1406 에디터

이형석·2024년 1월 24일

알고리즘 Phase1

목록 보기
4/59
  • Iterator는 한 element를 가리키는게 아니라 element와 element의 사이에 있음(커서처럼)
  • LinkedList를 구현한 Collection객체는 ListIterator사용가능
  • ListIterator<?> it = list.listIterator();
  • 함수 :
    hasNext(), next(),
    hasPrevious(), previous(),
    add(), 일반적으로 키보드입력하는 것처럼, 커서위치에 입력하고 커서는 그 뒤로 감
    remove()
    커서 뒤에 있는 element에 대해 실행

'B' 명령어인 경우 왼쪽에 있는 문자를 삭제해야 하는데,
ListIterator의 remove()는 현재 오른쪽을 대상으로 삭제하므로 previous()로 이동한 후 실행해야 하는 점 주의

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String str = br.readLine();
        LinkedList<Character> list = new LinkedList<>();
        for(int i = 0; i < str.length(); i++){
            list.add(str.charAt(i));
        }
        
        int commandN = Integer.parseInt(br.readLine());
        
        ListIterator<Character> it = list.listIterator();
        while(it.hasNext()){
            it.next();
        }
        
        for(int i = 0; i < commandN; i++){
            String command = br.readLine();
            if(command.equals("L")){
                if(it.hasPrevious()){
                    it.previous();
                }
            }else if(command.equals("D")){
                if(it.hasNext()){
                    it.next();
                }
            }else if(command.equals("B")){
                if(it.hasPrevious()){
                    it.previous();
                    it.remove();
                }
            }else{    // firstChar == P
                it.add(command.charAt(2));
            }
        }
        StringBuilder sb = new StringBuilder("");
        while(!list.isEmpty()){
            sb.append(list.poll());
        }
        System.out.println(sb);
    }
}
profile
금융IT 개발자

0개의 댓글