Skip to content

Commit

Permalink
feat: reverse Linked List method
Browse files Browse the repository at this point in the history
  • Loading branch information
201flaviosilva committed May 26, 2023
1 parent 72ec0a6 commit a881a19
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/DataStructures/LinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,20 @@ export class LinkedList {
}

reverse() {
let temp = this.head;
this.head = this.tail;
this.tail = temp;

let prev = null;
let next = null;

for (let i = 0; i < this.size; i++) {
next = temp.next;
temp.next = prev;
prev = temp;
temp = next;
}

return this;
}

Expand Down
16 changes: 16 additions & 0 deletions tests/DataStructures/LinkedList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,22 @@ describe("LinkedList.js", () => {
});
});

describe("reverse()", () => {
it("should reverse the linkedlist", () => {
const ll = new LinkedList(0);
ll.push(10);
ll.push(200);
ll.push(3000);

ll.reverse();

expect(ll.head.value).toBe(3000);
expect(ll.tail.value).toBe(0);

expect(ll.toArray()).toEqual([3000, 200, 10, 0]);
});
});

describe("toArray()", () => {
it("should return an array with the values of the linked list", () => {
const ll = new LinkedList(0);
Expand Down

0 comments on commit a881a19

Please sign in to comment.