Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit eacbd9f

Browse files
author
Swastikyadav
committed
Add remvoeFirst and removeLast method in linkedList class
1 parent b3a6af9 commit eacbd9f

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

‎18-linkedList.js‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,33 @@ class LinkedList {
6464
clear() {
6565
this.head = null;
6666
}
67+
68+
// RemoveFirst - Removes the first node and sets the head to second node.
69+
removeFirst() {
70+
if (!this.head) return;
71+
72+
this.head = this.head.next;
73+
}
74+
75+
// RemoveLast - Removes the last node (the tail).
76+
removeLast() {
77+
let currentNode = this.head;
78+
let previousNode = null;
79+
80+
if (!this.head) return null;
81+
82+
if (!this.head.next) {
83+
this.head = null;
84+
return;
85+
}
86+
87+
while (currentNode.next) {
88+
previousNode = currentNode;
89+
currentNode = currentNode.next;
90+
}
91+
92+
previousNode.next = null;
93+
}
6794
}
6895

6996
// -------------------------
@@ -75,10 +102,12 @@ list.head = nodeOne;
75102
list.insertFirst(15);
76103

77104
console.log(list);
78-
console.log(list.size());
79-
console.log(list.getFirst());
80-
console.log(list.getLast());
105+
// console.log(list.size());
106+
// console.log(list.getFirst());
107+
// console.log(list.getLast());
81108

82-
list.clear();
109+
// list.clear();
110+
// list.removeFirst();
111+
list.removeLast();
83112

84113
console.log(list);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /