Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- constructor(value, next = null) {
- this.value = value;
- this.next = next;
- }
- }
- class SLL {
- constructor() {
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
- add(value) {
- const node = new Node(value);
- let currentNode = this.head;
- if (!currentNode) {
- this.head = node;
- this.tail = node;
- this.length++;
- return node;
- } else {
- while (currentNode.next) {
- currentNode = currentNode.next
- }
- currentNode.next = node;
- this.tail = node;
- this.length++;
- return node;
- }
- }
- traverse() {
- let currentNode = this.head;
- for (let i = 0; i < this.length; i++) {
- console.log(currentNode.value);
- currentNode = currentNode.next;
- }
- }
- remove(location) {
- if (location === 0) { // we want to delete first element
- this.head = this.head.next;
- this.length--;
- if (this.length === 0) { // if there are no more nodes in this list
- this.tail = null;
- }
- } else { //if any inside node is to be deleted
- let currentNode = this.head;
- for (let i = 0; i < location - 1; i++) {
- currentNode = currentNode.next; // we need to traverse till we find the location
- }
- currentNode.next = currentNode.next.next; // delete the required node
- this.tail = currentNode;
- this.length--;
- } //end of else
- }
- }
- const node = new SLL();
- node.add(5);
- node.add(9);
- node.add(15);
- node.traverse();
- // console.log(JSON.stringify(node, 0, 2))
- // node.remove(2);
- // console.log(JSON.stringify(node, 0, 2))
- // node.remove(1);
- // console.log(JSON.stringify(node, 0, 2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement