Skip to content

Refactor linked list #19

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

Merged
merged 3 commits into from
Feb 3, 2019
Merged
Changes from all 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
9 changes: 6 additions & 3 deletions src/linked-list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const stringifyDefault = (value: any) => {
return `${value}`
}

export type ICompareFunction = (nodeValue: any) => boolean

export class LinkedList {
public head: Node | null
public tail: Node | null
Expand Down Expand Up @@ -69,7 +71,7 @@ export class LinkedList {
* @param compare 查找函数
* @returns {INode|null} 找到的节点或者null
*/
public find(value: any, compare?: (nodeValue: any) => boolean): Node | null {
public find(value: any, compare?: ICompareFunction): Node | null {
let currentNode = this.head
if (compare) {
while (currentNode !== null && !compare(currentNode.value)) {
Expand Down Expand Up @@ -148,15 +150,16 @@ export class LinkedList {
* @param {any} value
* @returns {INode|null} 返回最后一个被删除的节点,没有则返回null
*/
public delete(value: any) {
public delete(value: any, compare?: ICompareFunction) {
if (!this.head) {
return null
}

let deletedNode = null
compare = compare || ((nodeValue: any): boolean => nodeValue === value)

// 查看head是不是需要删除的node
while (this.head && this.head.value === value) {
while (this.head && compare(this.head.value)) {
deletedNode = this.head
this._length--
this.head = this.head.next
Expand Down