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

modified insert method in linked list and .eslintrc #1053

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
"env": {
"jest/globals": true
},
"ignorePatterns": ["*.md", "*.png", "*.jpeg", "*.jpg"],
"rules": {
"no-bitwise": "off",
"no-lonely-if": "off",
"class-methods-use-this": "off",
"arrow-body-style": "off",
"no-loop-func": "off"
"no-loop-func": "off",
"linebreak-style": ["error", "windows"]
},
"settings": {
"react": {
Expand Down
49 changes: 28 additions & 21 deletions src/data-structures/linked-list/LinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,27 +63,32 @@ export default class LinkedList {
const index = rawIndex < 0 ? 0 : rawIndex;
if (index === 0) {
this.prepend(value);
return this;
}
// if we have single node in linked list and we have to insert a value we can insert at last
if (this.head === this.tail) {
this.append(value);
return this;
}
const newNode = new LinkedListNode(value);
let count = 1;
let currentNode = this.head;

while (currentNode) {
if (count === index) break;
currentNode = currentNode.next;
count += 1;
}
// if there is a node in the position we want to insert
if (currentNode) {
newNode.next = currentNode.next;
currentNode.next = newNode;
} else {
let count = 1;
let currentNode = this.head;
const newNode = new LinkedListNode(value);
while (currentNode) {
if (count === index) break;
currentNode = currentNode.next;
count += 1;
}
if (currentNode) {
newNode.next = currentNode.next;
currentNode.next = newNode;
} else {
if (this.tail) {
this.tail.next = newNode;
this.tail = newNode;
} else {
this.head = newNode;
this.tail = newNode;
}
}
/* if index exceeds the size of linked list we
will be appending the node at last or if the linked
list dosent exist we will be appending the value that
means inserting a new value into the linked list */
this.append(value);
}
return this;
}
Expand Down Expand Up @@ -239,7 +244,9 @@ export default class LinkedList {
* @return {string}
*/
toString(callback) {
return this.toArray().map((node) => node.toString(callback)).toString();
return this.toArray()
.map((node) => node.toString(callback))
.toString();
}

/**
Expand Down