Data Structures: Linked List Stack in TypeScript

Unraveling the Linked List Stack in TypeScript

Introduction

Let's get right into the meat and potatoes. The Linked List Stack, and we're doing it in TypeScript. Whether you're a seasoned pro or just starting, this guide aims to shed light on this data structure.

What is a Linked List Stack?

Understanding the Basics

A Linked List Stack is a dynamic data structure, combining the concepts of stacks and linked lists. It's like a stack of dishes, but with a twist. Each dish (node) knows the position of the next one. There are different variations of the methods in each one. And I am in no way proclaiming this has the best methods. It most assuredly isn't. This is to give you what you need so that you understand it.

Why Use a Linked List Stack?

  • Flexibility: It grows and shrinks as needed. No size limitations here!
  • Efficiency: Adding or removing elements? It's a breeze and happens in O(1) time.

The Linked List with Tail

It may actually be a bit of a cop out, but we will be using the linked list with tail here. So if you aren't familiar with it, read the following linked list with tail article and come back here. Because the implementation of both this, and the linked list queue will both be using the linked list tail. We merely change some of the methods up.

Implementing a Linked List Stack in TypeScript

Setting the Stage

Since we are using the linked list with tail, we do not need to create the node class. But it does exist, and it is there. But all of that is already being taken care of.


import { LinkedListWithTail } from "./linkedListWithTail.js" // our cop out

class LinkedListStack {
	list: LinkedListWithTail

	constructor() {
		this.list = new LinkedListWithTail()
	}
}

Pushing Elements


push(value: any) {
	this.list.prepend(value)
}

Popping Elements


pop() {
	return this.list.removeFromFront()
}

Peeking


peek() {
	return this.list.head?.value
}


isEmpty() ?


isEmpty() {
	return this.list.isEmpty()
}


getSize()


getSize() {
	return this.list.getSize()
}

print()


print() {
	this.list.print()
}

Practical Examples

Example 1: Storing Usernames

Imagine you're tracking users logging in and out of a system.


const userStack = new LinkedListStack<string>();
userStack.push("Alice");
userStack.push("Bob");

Example 2: Undo Feature in an App

Implementing an undo feature? A stack is your friend.


const actionStack = new LinkedListStack<string>();
actionStack.push("Draw Line");
actionStack.push("Erase");

Conclusion

The Linked List Stack in TypeScript is a versatile and efficient data structure. It's like having a magic bag that expands and shrinks as needed, all while keeping things in order. Dive in, experiment, and watch your code efficiency soar!