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

algorithm: find the middle of linked-list#1096

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
raklaptudirm merged 5 commits intoTheAlgorithms:masterfrom10kartik:develop
Sep 10, 2022
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletionData-Structures/Linked-List/SinglyLinkedList.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -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) {
Expand DownExpand Up@@ -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
Expand Down
23 changes: 23 additions & 0 deletionsData-Structures/Linked-List/test/SinglyLinkedList.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,29 @@ describe('SinglyLinkedList', () => {
expect(list.size()).toBe(1)
})

it('Middle node of linked list', () => {
const list = new LinkedList()
list.addFirst(1)

// Middle node for list having single node
expect(list.findMiddle().data).toEqual(1)

list.addLast(2)
list.addLast(3)
list.addLast(4)
list.addLast(5)
list.addLast(6)
list.addLast(7)

// Middle node for list having odd number of nodes
expect(list.findMiddle().data).toEqual(4)

list.addLast(10)

// Middle node for list having even number of nodes
expect(list.findMiddle().data).toEqual(5)
})

it('Check Iterator', () => {
const list = new LinkedList()

Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp