[24.01.18] Today CS 공부 [배열,링크드리스트]

Seong Hyeon Kim·2024년 1월 18일
0

CS스터디

목록 보기
8/9

배열(Array)

배열(Array)

장점:

  • 인덱스를 통한 빠른 임의 접근이 가능합니다. 즉, 배열의 특정 위치에 있는 요소를 직접 접근할 수 있습니다.

  • 고정된 크기를 가질 수 있으며, 메모리 관리가 상대적으로 간편합니다.

단점:

  • 배열의 크기를 동적으로 조절하기 위해서는 배열의 복사 및 재할당이 필요하며, 이는 성능 손실을 초래할 수 있습니다.

  • 중간에 요소를 삽입하거나 삭제할 경우, 해당 위치 이후의 모든 요소를 이동시켜야 하므로 시간 복잡도가 높아집니다.


링크드 리스트(Linked List)

링크드 리스트(Linked List)

장점:

  • 요소를 삽입하거나 삭제할 때, 해당 요소만을 조작하면 되기 때문에 배열보다 효율적입니다.
  • 크기를 동적으로 조절할 수 있으며, 메모리는 필요에 따라 할당됩니다.

단점:

  • 임의의 요소에 접근하기 위해서는 처음부터 순차적으로 접근해야 하므로 배열에 비해 느린 접근 시간이 소요될 수 있습니다.

  • 각 노드마다 다음 노드의 주소를 저장해야 하므로 메모리 소비가 높을 수 있습니다.


코드예시

배열


// 배열 생성
let myArray = [1, 2, 3, 4, 5];

// 요소 추가
myArray.push(6);

// 요소 삭제
myArray.pop();

// 임의의 위치에 요소 추가
myArray.splice(2, 0, 7);

// 배열 출력
console.log(myArray);

배열에 특징을 나타내기 위한 코드로 인덱스로 접근하는 방법과, 고정된 크기를 미리 지정해주는 코드들 입니다.

배열은 내장된 push, pop, splice 등의 메서드를 사용하여 요소를 조작할 수 있습니다

링크드 리스트


// 링크드 리스트 노드 생성
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

// 링크드 리스트 생성
class LinkedList {
  constructor() {
    this.head = null;
  }

  // 노드 추가
  addNode(data) {
    const newNode = new Node(data);

    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
  }

  // 노드 삭제
  deleteNode(data) {
    if (!this.head) {
      return;
    }

    if (this.head.data === data) {
      this.head = this.head.next;
      return;
    }

    let current = this.head;
    let prev = null;

    while (current && current.data !== data) {
      prev = current;
      current = current.next;
    }

    if (!current) {
      return; // 노드가 없음
    }

    prev.next = current.next;
  }

  // 링크드 리스트 출력
  printList() {
    let current = this.head;
    while (current) {
      console.log(current.data);
      current = current.next;
    }
  }
}

// 링크드 리스트 사용 예제
let myList = new LinkedList();
myList.addNode(1);
myList.addNode(2);
myList.addNode(3);

myList.deleteNode(2);

myList.printList();

링크드 리스트는 직접 노드를 추가하고 삭제하는 메서드를 정의해야 합니다. 링크드 리스트에서는 임의의 위치에 직접 접근할 수 없으며, 순차적으로 노드를 탐색해야 합니다.





let myList = new LinkedList();
console.log('초기값 => ',myList)

myList.printList()

myList.addNode(1);
console.log('1 추가후 => ',myList)
console.log(' ')


myList.addNode(2);
console.log('2 추가후 => ',myList)
console.log(' ')

myList.addNode(3);
console.log('3 추가후 => ',myList)
console.log(' ')

console.log('- 프린트 리스트 -')
myList.printList()

콘솔로그로 한번더 확인해보면 잘 작동하는 것도 볼수 있고 원하는데로 생성과 추가가 잘 되는것 역시 확인할 수 있습니다

profile
삽질도 100번 하면 요령이 생긴다. 부족한 건 경험으로 채우는 백엔드 개발자

0개의 댓글