Skip to content

Commit

Permalink
feat(LinkedList): add reverse
Browse files Browse the repository at this point in the history
  • Loading branch information
sun0day committed Oct 12, 2022
1 parent 626db0d commit b0b8536
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/linked-list/index.test.ts
Expand Up @@ -113,4 +113,20 @@ describe('LinkedList', () => {
expect(list.size()).toBe(0)
expect(list.toArray()).toEqual([])
})

it('should reverse', () => {
let list = new LinkedList()
list.reverse()
expect(list.toArray()).toEqual([])

list = LinkedList.from([1])
list.reverse()
expect(list.toArray()).toEqual([1])
expect(list.tail().value).toBe(1)

list = LinkedList.from([1, 2, 3])
list.reverse()
expect(list.toArray()).toEqual([3, 2, 1])
expect(list.tail().value).toBe(1)
})
})
20 changes: 20 additions & 0 deletions packages/linked-list/index.ts
Expand Up @@ -174,6 +174,26 @@ export class LinkedList<T> {
return cur
}

/**
* reverse a linked list, T = O(n)
*
* @returns {LinkedList<T>} - linked list after reverse
*/
reverse() {
let prev = null; let cur = this._head; let next = null

while (cur) {
next = cur.next
cur.next = prev

prev = cur
cur = next
}

this._tail = this._head
this._head = prev
}

/**
* get head node
*
Expand Down

0 comments on commit b0b8536

Please sign in to comment.