Movatterモバイル変換


[0]ホーム

URL:


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

Commit6ad2467

Browse files
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>
1 parent644d7f7 commit6ad2467

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

‎Data-Structures/Linked-List/SinglyLinkedList.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* a singly linked list.
77
*/
88

9-
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, get, clean
9+
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt,findMiddle,get, clean
1010

1111
classNode{
1212
constructor(data){
@@ -193,6 +193,19 @@ class LinkedList {
193193
returnremovedNode.data
194194
}
195195

196+
// Returns a reference to middle node of linked list
197+
findMiddle(){
198+
// If there are two middle nodes, return the second middle node.
199+
letfast=this.headNode
200+
letslow=this.headNode
201+
202+
while(fast!==null&&fast.next!==null){
203+
fast=fast.next.next
204+
slow=slow.next
205+
}
206+
returnslow
207+
}
208+
196209
// make the linkedList Empty
197210
clean(){
198211
this.headNode=null

‎Data-Structures/Linked-List/test/SinglyLinkedList.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,29 @@ describe('SinglyLinkedList', () => {
164164
expect(list.size()).toBe(1)
165165
})
166166

167+
it('Middle node of linked list',()=>{
168+
constlist=newLinkedList()
169+
list.addFirst(1)
170+
171+
// Middle node for list having single node
172+
expect(list.findMiddle().data).toEqual(1)
173+
174+
list.addLast(2)
175+
list.addLast(3)
176+
list.addLast(4)
177+
list.addLast(5)
178+
list.addLast(6)
179+
list.addLast(7)
180+
181+
// Middle node for list having odd number of nodes
182+
expect(list.findMiddle().data).toEqual(4)
183+
184+
list.addLast(10)
185+
186+
// Middle node for list having even number of nodes
187+
expect(list.findMiddle().data).toEqual(5)
188+
})
189+
167190
it('Check Iterator',()=>{
168191
constlist=newLinkedList()
169192

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp