스택 데이터 구조 이해: JavaScript에서 스택 구현을 위한 단계별 가이드

Linda Hamilton
풀어 주다: 2024-10-09 08:21:30
원래의
355명이 탐색했습니다.

스택은 접시 더미처럼 작동하는 간단한 선형 데이터 구조입니다. 이는 후입선출(LIFO) 원칙을 따릅니다. 접시 더미라고 생각하세요. 더미 꼭대기에서만 접시를 추가하거나 제거할 수 있습니다.

스택에 대한 더 나은 이해를 위해 짧은 상상 여행을 떠나볼까요?.
당신이 멋진 레스토랑에 있다고 상상해 보세요 ?️, 주방 직원이 바쁜 밤을 준비하고 있나요 ?‍?. 접시 공간에는 사용을 기다리는 접시가 높이 쌓여 있습니다. 손님이 도착하고 주문이 쏟아져 들어오면 직원이 접시 더미 위에서 접시를 가져옵니다. 깨끗한 접시를 추가하면 바로 위에 올려집니다. 이 간단한 시스템을 통해 가장 오래 머물렀던 맨 아래의 접시를 마지막에 사용하고, 맨 위에 있는 갓 청소한 접시를 먼저 사용하게 됩니다 ✨.

Understanding Stack Data Structure: A Step-by-Step Guide to Implementing Stack in JavaScript

이것이 본질적으로 스택 데이터 구조가 작동하는 방식입니다. 스택은 LIFO(Last In First Out) 원칙을 따르는 선형 데이터 구조입니다. 접시 더미와 마찬가지로 스택에 마지막으로 추가된 항목이 가장 먼저 제거됩니다.

목차

스택 데이터 구조에 대한 이 포괄적인 튜토리얼에서는 간단하고 초보자 친화적인 접근 방식으로 다음 주제를 살펴보겠습니다.

  1. 스택이란 무엇인가요?
  2. 스택 사용의 장점과 단점
  3. 스택의 실제 응용
  4. 스택의 주요 작업
  5. JavaScript로 스택 구현
  6. 결론


준비됐나요? 뛰어들어 보세요

Understanding Stack Data Structure: A Step-by-Step Guide to Implementing Stack in JavaScript

스택이란 무엇입니까?

스택은 LIFO(후입선출) 원칙을 따르는 선형 데이터 구조입니다. 즉, 스택에 마지막으로 추가된 요소가 가장 먼저 제거됩니다. 책 더미처럼 생각하세요. 책 더미 맨 위에서만 책을 추가하거나 제거할 수 있습니다.

스택 사용의 장단점

흐름을 계속 진행하고 코드를 작성하기 전에 스택을 사용할 수 없는 위치와 위치를 이해하는 것이 좋습니다. 아래 표에는 스택의 장점과 단점이 자세히 나와 있습니다.

Pros Cons
Simple and easy to implement Limited access (only top element is directly accessible)
Efficient for Last-In-First-Out (LIFO) operations Not suitable for random access of elements
Constant time O(1) for push and pop operations Can lead to stack overflow if not managed properly
Useful for tracking state in algorithms (e.g., depth-first search) Not ideal for searching or accessing arbitrary elements
Helps in memory management (e.g., call stack in programming languages) Fixed size in some implementations (array-based stacks)
Useful for reversing data May require resizing in dynamic implementations, which can be costly
Supports recursive algorithms naturally Not efficient for large datasets that require frequent traversal
Helps in expression evaluation and syntax parsing Potential for underflow if pop operation is called on an empty stack
Useful in undo mechanisms in software Limited functionality compared to more complex data structures
Efficient for certain types of data organization (e.g., browser history) Not suitable for problems requiring queue-like (FIFO) behavior

Key Operations on a Stack

The fundamental operations that can be performed on a stack are:

  1. push(): Adds an element to the top of the stack.
  2. pop(): Removes the topmost element from the stack.
  3. peek(): Returns the top element of the stack without removing it.
  4. isEmpty(): Checks if the stack is empty.
  5. size(): Returns the number of elements in the stack.

Real-World Applications of Stacks

Stacks are every where in computer science and software development. Here are some common applications:

  1. Undo Functionality: In text editors or graphic design software, each action is pushed onto a stack. When you hit "undo," the most recent action is popped off the stack and reversed.

  2. Browser History: When you visit a new page, it's pushed onto a stack. The "back" button pops the current page off the stack, revealing the previous one.

  3. Function Call Stack: In programming languages, function calls are managed using a stack. When a function is called, it's pushed onto the call stack. When it returns, it's popped off.

  4. Expression Evaluation: Stacks are used to evaluate arithmetic expressions, especially those in postfix notation.

  5. Backtracking Algorithms: In problems like maze-solving or puzzle-solving, stacks can keep track of the path taken, allowing easy backtracking when needed.

Stack Implementation in JavaScript

Now, let's implement a Stack in JavaScript. It is important to know that there are different ways to implement a stack in JavaScript. One of the common ways to implement a stack is using array, another way is to use linked list. In this article, we'll implement a stack using linked list (singly linked list).

Implement Stack using Linked List

I hope you still remember how linked list works? You might need to check out the linked list implementation in one of our previous articles in this same series.

이제 단일 연결 리스트를 사용하여 스택 구현을 시작해 보겠습니다. 할까요?

Understanding Stack Data Structure: A Step-by-Step Guide to Implementing Stack in JavaScript

먼저 스택 개별 항목을 나타내는 Node 클래스를 만듭니다.

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}
로그인 후 복사

그런 다음 스택을 나타내는 Stack 클래스를 생성하겠습니다.

class Stack {
  constructor() {
    this.top = null;
    this.size = 0;
  }

  // Stack Operations will be implemented here ?
}
로그인 후 복사

푸시 작업

푸시 작업은 스택 상단에 새 요소를 추가합니다. 새 StackNode를 생성하고 다음 포인터를 현재 상단으로 설정한 다음 이 새 노드를 가리키도록 상단을 업데이트합니다. 마지막으로 크기가 증가합니다.

  // Push element to the top of the stack
  push(element) {
    const newNode = new Node(element);
    newNode.next = this.top;
    this.top = newNode;
    this.size++;
  }
로그인 후 복사

팝 오퍼레이션

팝 작업은 스택의 최상위 요소를 제거합니다. 먼저 스택이 비어 있는지 확인합니다. 그렇다면 오류 메시지를 반환합니다. 그렇지 않으면 상단 요소를 제거하고 상단 포인터를 다음 노드로 업데이트하고 크기를 줄입니다. 마지막으로 제거된 요소를 반환합니다.

  // Remove and return the top element
  pop() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    const poppedElement = this.top.data;
    this.top = this.top.next;
    this.size--;
    return poppedElement;
  }
로그인 후 복사

엿보기 작업

Peek 작업은 최상위 요소를 제거하지 않고 반환합니다. 먼저 스택이 비어 있는지 확인합니다. 그렇다면 오류 메시지를 반환합니다. 그렇지 않으면 최상위 요소의 데이터를 반환합니다.

  // Return the top element without removing it
  peek() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    return this.top.data;
  }
로그인 후 복사

isEmpty 작업

isEmpty 작업은 스택이 비어 있는지 확인합니다. 스택이 비어 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

  // Check if the stack is empty
  isEmpty() {
    return this.size === 0;
  }
로그인 후 복사

getSize 작업

getSize 작업은 스택 크기를 반환합니다. 스택의 요소 수를 반환합니다.

  // Return the size of the stack
  getSize() {
    return this.size;
  }
로그인 후 복사

인쇄 작업

인쇄 작업은 스택을 인쇄합니다. 최상위 요소의 데이터를 반환합니다.

  // Print the stack
  print() {
    let current = this.top;
    let result = "";
    while (current) {
      result += current.data + " ";
      current = current.next;
    }
    console.log(result.trim());
  }
로그인 후 복사

사용예

// Usage example
const customStack = new CustomStack();
customStack.push(10);
customStack.push(20);
customStack.push(30);
console.log(customStack.pop()); // 30
console.log(customStack.peek()); // 20
console.log(customStack.getSize()); // 2
console.log(customStack.isEmpty()); // false
customStack.print(); // 20 10
로그인 후 복사

이 구현에서는 연결된 목록 (단일 연결 목록) 구조를 사용하여 스택을 나타냈습니다. 각 요소는 데이터 값과 다음 노드에 대한 참조가 있는 노드입니다. 스택의 맨 위는 항상 가장 최근에 추가된 노드입니다.

결론

스택은 LIFO(후입선출) 원칙을 따르는 컴퓨터 과학의 기본 데이터 구조입니다. 함수 호출 관리, 실행 취소 기능 구현, 산술 표현식 평가 등 다양한 애플리케이션에 사용됩니다.

이 튜토리얼에서는 스택의 기본 사항, 스택 사용의 장단점, JavaScript에서의 구현(연결된 목록 사용)을 다루었습니다. 스택을 이해하는 것은 스택을 구현하는 방법을 아는 것뿐만 아니라 스택이 문제 해결을 위한 올바른 도구인지 인식하는 것이기도 합니다.

소프트웨어 개발 여정을 계속하다 보면 스택이 문제 해결 툴킷에서 없어서는 안 될 도구라는 것을 알게 될 것입니다. 간단하면서도 강력하며, 이를 익히면 효율적인 알고리즘과 데이터 구조를 설계하는 능력이 크게 향상됩니다.



최신 소식과 연결 상태를 유지하세요

이 시리즈의 모든 부분을 놓치지 않도록 저와 연결하여 소프트웨어 개발(웹, 서버, 모바일 또는 스크래핑/자동화), 데이터 구조 및 알고리즘, 기타 흥미로운 기술에 대한 심층적인 토론을 원합니다. 주제에 대해서는 저를 팔로우하세요:

  • 깃허브
  • 링크드인
  • 엑스(트위터)

앞으로 계속 지켜봐 주시기 바랍니다. 즐거운 코딩 되세요 ?‍??

로그인 후 복사

위 내용은 스택 데이터 구조 이해: JavaScript에서 스택 구현을 위한 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!