Stacks

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) methodology, meaning the last element added to the stack will be the first one to be removed. This structure is analogous to a stack of plates where you can only take the top plate off.

Implementing a Stack

Basic Structure:

In JavaScript, a stack can be easily implemented using an array.

Example:

javascript
	class Stack {
	  constructor() {
	    this.items = [];
	  }
	
	  // Add element to the stack
	  push(element) {
	    this.items.push(element);
	  }
	
	  // Remove and return the top element of the stack
	  pop() {
	    if (this.items.length === 0) return 'Stack is empty';
	    return this.items.pop();
	  }
	
	  // View the top element of the stack
	  peek() {
	    return this.items[this.items.length - 1];
	  }
	
	  // Check if the stack is empty
	  isEmpty() {
	    return this.items.length === 0;
	  }
	
	  // Get the size of the stack
	  size() {
	    return this.items.length;
	  }
	
	  // Clear the stack
	  clear() {
	    this.items = [];
	  }
	}

Practical Example: Using the Stack

Let’s use the Stack class in a practical scenario. Suppose we are managing browser history where the most recent page visited is the first to be revisited.

javascript
	// Create a new stack instance
	let browserHistory = new Stack();
	
	// Visit some websites
	browserHistory.push('Homepage');
	browserHistory.push('Article Page');
	browserHistory.push('Contact Us');
	
	// Go back to the last page
	console.log('Revisiting: ' + browserHistory.pop());
	
	// Check the current page
	console.log('Current Page: ' + browserHistory.peek());

Expected Output:

txt
	Revisiting: Contact Us
	Current Page: Article Page

In this example, each time a new page is visited, it’s pushed onto the browserHistory stack. The pop method is used to go back, simulating a user hitting the back button in a browser.

Advantages in Practical Use

  • Simple and Efficient: Stacks are straightforward to implement and provide efficient operations for LIFO scenarios.
  • Useful in Algorithms: Stacks are used in various algorithms, including parsing, tree traversals, and backtracking algorithms.

Limitations:

  • Limited Access: Stacks don’t allow random access to their elements. You can only access the top element.

Further Learning:

For more in-depth study and additional stack operations, these resources can be valuable: