gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)
give code of linked list in typescript
- User
give code of linked list in typescript
- Assistant
Certainly! Below is a simple implementation of a singly linked list in TypeScript. This example includes basic methods for adding nodes, removing nodes, and displaying the list.
class Node<T> { public data: T; public next: Node<T> | null; constructor(data: T) { this.data = data; this.next = null; } } class LinkedList<T> { private head: Node<T> | null; constructor() { this.head = null; } // Add a node to the end of the list public add(data: T): void { const newNode = new Node(data); if (!this.head) { this.head = newNode; return; } let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } // Remove a node from the list public remove(data: T): void { if (!this.head) return; // If the head needs to be removed if (this.head.data === data) { this.head = this.head.next; return; } let current = this.head; while (current.next) { if (current.next.data === data) { current.next = current.next.next; return; } current = current.next; } } // Display the linked list public display(): void { let current = this.head; while (current) { process.stdout.write(`${current.data} -> `); current = current.next; } console.log('null'); } // Get the size of the linked list public size(): number { let count = 0; let current = this.head; while (current) { count++; current = current.next; } return count; } } // Example usage const linkedList = new LinkedList<number>(); linkedList.add(10); linkedList.add(20); linkedList.add(30); linkedList.display(); // Output: 10 -> 20 -> 30 -> null linkedList.remove(20); linkedList.display(); // Output: 10 -> 30 -> null console.log(`Size of the list: ${linkedList.size()}`); // Output: Size of the list: 2Explanation
- Node: This class represents each node in the linked list. It contains the
dataand a pointer/reference to the next node (next). - LinkedList: This class manages the linked list and provides methods to add, remove, display, and get the size of the list.
- add: Adds a new node to the end of the linked list.
- remove: Removes a node by value.
- display: Prints the current linked list.
- size: Returns the number of nodes in the linked list.
This is a basic implementation. Depending on your needs, you might want to extend it with more functionalities like reversing the list, finding the middle, etc.
- Node: This class represents each node in the linked list. It contains the