mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
algorithm: find the middle of linked-list (#1096)
* Added Middle of linked-list implementation. * Added Middle of LL function and tests * Refactor: Added method in singly LL and its tests * Refactor: Method name and inline test calls * Use `!== null` instead of `!= null` Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
@ -6,7 +6,7 @@
|
||||
* a singly linked list.
|
||||
*/
|
||||
|
||||
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, get, clean
|
||||
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, findMiddle, get, clean
|
||||
|
||||
class Node {
|
||||
constructor (data) {
|
||||
@ -193,6 +193,19 @@ class LinkedList {
|
||||
return removedNode.data
|
||||
}
|
||||
|
||||
// Returns a reference to middle node of linked list
|
||||
findMiddle () {
|
||||
// If there are two middle nodes, return the second middle node.
|
||||
let fast = this.headNode
|
||||
let slow = this.headNode
|
||||
|
||||
while (fast !== null && fast.next !== null) {
|
||||
fast = fast.next.next
|
||||
slow = slow.next
|
||||
}
|
||||
return slow
|
||||
}
|
||||
|
||||
// make the linkedList Empty
|
||||
clean () {
|
||||
this.headNode = null
|
||||
|
Reference in New Issue
Block a user