알고리즘 기초 - 3 (Data Structure)

Hansoo Kim·2020년 4월 20일
0
  1. queue

    class Queue {
      constructor() {
        this.data = [];
      }
      add(record) {
        this.data.unshift(record);
      }
      remove(record) {
        return this.data.pop();
      }
      peek() {
        return this.data[this.data.length - 1];
      }
    }
  2. weave

    const Queue = require('./queue');
    
    function weave(sourceOne, sourceTwo) {
      const q = new Queue();
      while (sourceOne.peek() || sourceTwo.peek()) {
        if (sourceOne.peek()) {
          q.add(sourceOne.remove());
        }
    
        if (sourceTwo.peek()) {
          q.add(sourceTwo.remove());
        }
      }
      return q;
    }
  3. stack

    class Stack {
      constructor() {
        this.data = [];
      }
      push(record) {
        this.data.push(record);
      }
      pop() {
        return this.data.pop();
      }
      peek() {
        return this.data[this.data.length - 1];
      }
    }
  4. qfroms (queue from stack) - queue 2개로 stack 만들기

    const Stack = require('./stack');
    
    class Queue {
      constructor() {
        this.first = new Stack();
        this.second = new Stack();
      }
    
      add(record) {
        this.first.push(record);
      }
    
      remove() {
        while (this.first.peek()) {
          this.second.push(this.first.pop());
        }
        const record = this.second.pop();
        while (this.second.peek()) {
          this.first.push(this.second.pop());
        }
        return record;
      }
    
      peek() {
        while (this.first.peek()) {
          this.second.push(this.first.pop());
        }
    
        const record = this.second.peek();
        while (this.second.peek()) {
          this.first.push(this.second.pop());
        }
        return record;
      }
    }

0개의 댓글