inflearn logo
강의

Course

Instructor

Non-majors catching up with majors - Data Structures (with JavaScript)

Implementing stacks and queues

숙제1 LinkedList로 스택 구현하기

251

rhkdtjd124829

138 asked

1

학습 목표

- 배열 치트키 자료구조가 아닌 연결 리스를 이용하여 stack 자료구조를 구현하자.

- 삽입과 삭제를 시간복잡도 O(1)가 되게 해야됨.

- stack은 FILO이기 때문에 삭제시 마지막을 삭제해야됨.

 

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
    this.prev = null;
  }
}

class LinkedList {
  constructor(length = 0) {
    this.length = length;
    this.head = null;
    this.tail = null;
  }

  add(value) {
    const newNode = new Node(value);
    if (this.head === null) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      newNode.prev = this.tail;
      this.tail.next = newNode;
      this.tail = newNode;
    }

    this.length++;
    return this.length;
  }

  removeLast() {
    const value = this.tail.value;
    this.tail.prev.next = null; // 제일 마지막 이전의 next의 좌표를 null로 변경해줌
    this.tail = this.tail.prev; // 마지막을 tail의 이전 노드로 변경 해줌

    return value;
  }
}

// 숙제 1 연결리스트로 스택 만들기
class Stack {
  linkedList = new LinkedList();

  add(value) {
    return this.linkedList.add(value);
  }

  pop() {
    return this.linkedList.removeLast();
  }

  get top() {
    return this.linkedList.head.value;
  }

  get length() {
    return this.linkedList.length;
  }
}

const stack = new Stack();
console.log(stack.add(1)); // 1
console.log(stack.add(3)); // 2
console.log(stack.add(5)); // 3

console.log(stack.top); // 1
console.log(stack.length); // 3
console.log(stack.pop()); // 5

결과

디버거 결과를 확인 해보면 최종적으로

tail의 value는 3이고 next는 null prev는 value1의 노드를 가르키고 있는걸 알 수 있다.

javascript 코딩-테스트 알고리즘

Answer 1

1

zerocho

박수!!!

0

rhkdtjd124829

감사합니다 !!! 😁

2주차 개념#12 트리 순회

0

14

2

프론트엔드 학습 수준 문의

0

22

2

백준 사이트 서비스 종료

0

38

3

잠겨버린 사물함 시간초과 관련 질문입니다.

0

17

1

스택, 큐 연결리스트로 구현 과제 완료입니다!

0

93

1

heapify 안의 bigger 삼항연산자 질문

0

116

2

LinkedList로 스택, 큐 구현하기 숙제

0

123

1

linkedList prev와 tail 사용 후 o(1) 구현.

0

165

1

숙제 : LinkedList로 Stack, Queue 구현하기

0

177

1

연결리스트 숙제

0

239

1

한번에 이해 안가는 제가 비정상 일까요...?

0

234

1

우선순위 큐 질문이 있습니다!

0

154

1

[숙제] minHeap 구현, maxHeap -> minHeap , minHeap -> maxHeap

1

235

1

최소힙 remove 구현하기

0

245

1

숙제 최소힙 만들기

0

152

1

숙제 length return 하기

0

194

1

숙제 : 같은 값을 넣은경우 에러 처리

0

181

1

영상 중간에 0:10 1:23초 수정에 따른 코드 최종본

1

143

1

숙제2 연결리스트를 이용하여 큐 구현하기

0

237

1

연결 리스트 구현 숙제 리뷰 부탁드려봅니다

1

345

2

let current = this.head 질문 있습니다!

0

251

1

퀴즈 답안

0

469

1

최소힙의 결과값과 최대힙->최소힙 결과값이 다른게 맞나요?

0

248

1

1주차 숙제에 대한 해답 코드는 따로 제공되지 않나요??

0

495

1