Skip to content

Commit 51de622

Browse files
committed
Added reverse-linked-list problem
1 parent 9a09f90 commit 51de622

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
1717
- [N Element From Last](src/_DataStructures_/LinkedList/element-from-last)
1818
- [Middle Node](src/_DataStructures_/LinkedList/middle-node)
1919
- [Detect Loop](src/_DataStructures_/LinkedList/loop-in-list)
20+
- [Reverse Linked List](src/_DataStructures_/LinkedList/reverse-linked-list)
2021
- [Stack](src/_DataStructures_/Stack)
2122
- [Implement Queue Using Stack](src/_DataStructures_/Stack/immitate-queue-using-stack)
2223
- [Baseball Game](src/_DataStructures_/Stack/baseball-game)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function reverseLinkedList(linkedList) {
2+
var next = linkedList.getFirst();
3+
var current = null;
4+
var prev;
5+
while(next != null){
6+
prev = current;
7+
current = next;
8+
next = next.next;
9+
current.next = prev;
10+
}
11+
return current;
12+
};
13+
module.exports = {
14+
reverseLinkedList,
15+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const { LinkedList } = require('../index');
2+
const { reverseLinkedList } = require('.').default;
3+
4+
describe('Reverse a LinkedList', () => {
5+
let list = null;
6+
beforeEach(() => {
7+
list = new LinkedList();
8+
list.addAtBeginning('1');
9+
list.addAtEnd('2');
10+
list.addAtEnd('3');
11+
list.addAtEnd('4');
12+
list.addAtEnd('5');
13+
});
14+
15+
it('Should return `null` for empty list', () => {
16+
list.delete();
17+
expect(reverseLinkedList(list)).toEqual(null);
18+
});
19+
20+
it('Should return `5`->`4`->`3`->`2`->`1` for the given list', () => {
21+
expect(reverseLinkedList(list).data).toEqual('5');
22+
expect(reverseLinkedList(list).next.data).toEqual('4');
23+
expect(reverseLinkedList(list).next.next.data).toEqual('3');
24+
expect(reverseLinkedList(list).next.next.next.data).toEqual('2');
25+
expect(reverseLinkedList(list).next.next.next.next.data).toEqual('1');
26+
});
27+
28+
it('Should return `3`->`2`->`1` after deleting 2 last nodes of the list', () => {
29+
list.removeFromEnd();
30+
list.removeFromEnd();
31+
expect(reverseLinkedList(list).data).toEqual('3');
32+
expect(reverseLinkedList(list).next.data).toEqual('2');
33+
expect(reverseLinkedList(list).next.next.data).toEqual('1');
34+
});
35+
});

0 commit comments

Comments
 (0)