Skip to content

Commit 6f27113

Browse files
committedSep 8, 2018
Add reverse() method for doubly linked list.
1 parent 80ecbe0 commit 6f27113

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
 

‎src/data-structures/doubly-linked-list/DoublyLinkedList.js

+28
Original file line numberDiff line numberDiff line change
@@ -230,4 +230,32 @@ export default class DoublyLinkedList {
230230
toString(callback) {
231231
return this.toArray().map(node => node.toString(callback)).toString();
232232
}
233+
234+
/**
235+
* Reverse a linked list.
236+
* @returns {DoublyLinkedList}
237+
*/
238+
reverse() {
239+
let currNode = this.head;
240+
let prevNode = null;
241+
let nextNode = null;
242+
243+
while (currNode) {
244+
// Store next node.
245+
nextNode = currNode.next;
246+
247+
// Change next node of the current node so it would link to previous node.
248+
currNode.next = prevNode;
249+
250+
// Move prevNode and currNode nodes one step forward.
251+
prevNode = currNode;
252+
currNode = nextNode;
253+
}
254+
255+
// Reset head and tail.
256+
this.tail = this.head;
257+
this.head = prevNode;
258+
259+
return this;
260+
}
233261
}

‎src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js

+26
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,30 @@ describe('DoublyLinkedList', () => {
228228
expect(node.value.customValue).toBe('test2');
229229
expect(linkedList.find({ value: 2, customValue: 'test5' })).toBeNull();
230230
});
231+
232+
it('should reverse linked list', () => {
233+
const linkedList = new DoublyLinkedList();
234+
235+
// Add test values to linked list.
236+
linkedList
237+
.append(1)
238+
.append(2)
239+
.append(3);
240+
241+
expect(linkedList.toString()).toBe('1,2,3');
242+
expect(linkedList.head.value).toBe(1);
243+
expect(linkedList.tail.value).toBe(3);
244+
245+
// Reverse linked list.
246+
linkedList.reverse();
247+
expect(linkedList.toString()).toBe('3,2,1');
248+
expect(linkedList.head.value).toBe(3);
249+
expect(linkedList.tail.value).toBe(1);
250+
251+
// Reverse linked list back to initial state.
252+
linkedList.reverse();
253+
expect(linkedList.toString()).toBe('1,2,3');
254+
expect(linkedList.head.value).toBe(1);
255+
expect(linkedList.tail.value).toBe(3);
256+
});
231257
});

0 commit comments

Comments
 (0)
Please sign in to comment.