Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problems involving Queues #81

Merged
merged 13 commits into from
Oct 13, 2019
Next Next commit
update: added tail of LL
  • Loading branch information
ashokdey committed Oct 13, 2019
commit a3d841e1ffbd319bb9c31d3c5bf9318de23ea7c1
36 changes: 20 additions & 16 deletions src/_DataStructures_/LinkedList/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,42 @@ class Node {
constructor(data, next) {
this.data = data;
this.next = next;
this.length = 0;
}
}

class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}

addAtBeginning(element) {
this.head = new Node(element, this.head);
if (!this.tail) {
this.tail = this.head;
}
return this.head;
}

addAtEnd(element) {
const node = new Node(element, null);

if (!this.head) {
this.head = node;
} else {
let address = this.head;
while (address.next) {
address = address.next;
}
address.next = node;
return this.addAtBeginning(element);
}
const node = new Node(element, null);
this.tail.next = node;
this.tail = node;
return node;
}

removeFromBeginning() {
if (!this.head) {
this.tail = null;
return null;
}
if (this.head.next === null) {
this.tail = this.head;
}
const node = this.head;
this.head = this.head.next;
return node;
Expand All @@ -47,8 +53,10 @@ class LinkedList {
address = address.next;
}

const node = address.next;
address.next = null;
this.tail = address;

const node = this.tail.next;
this.tail.next = null;
return node;
}

Expand All @@ -63,11 +71,7 @@ class LinkedList {
if (!this.head) {
return null;
}
let address = this.head;
while (address.next) {
address = address.next;
}
return address;
return this.tail;
}

getAt(index) {
Expand Down