Code coverage report for lib/algorithms/2-linkedLists/partition.js

Statements: 92.86% (26 / 28)      Branches: 80% (8 / 10)      Functions: 100% (1 / 1)      Lines: 96.3% (26 / 27)      Ignored: none     

All files » lib/algorithms/2-linkedLists/ » partition.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49        1 1   1 1 1 1 1   1   11 11   11 6 1 1   5 5     5 1 1   4 4       11     1 1         1     1
//2.4 Partition a linked list around a value x, where the values on the left
//    are less than x, and the values on the right are greater than or equal
//    to x.
 
var partition = function(head, x) {
	Iif (head === null) throw "Head is badful.";
 
	var leftStart = null;
	var leftEnd = null;
	var rightEnd = null;
	var rightStart = null;
	var current = head;
 
	while ( current != null ) {
 
		var next = current.next;
		current.next = null;
 
		if ( current.data <  x ) {
			if (leftStart === null) {
				leftStart = current;
				leftEnd = current;
			} else {
				leftEnd.next = current;
				leftEnd = current;
			}
		} else {
			if (rightStart === null) {
				rightStart = current;
				rightEnd = current;
			} else {
				rightEnd.next = current;
				rightEnd = current;
			}
		}
 
		current = next;
	}
 
	Eif(leftEnd != null) {
		leftEnd.next = rightStart;
	} else {
		leftStart = rightStart;
	}
 
	return leftStart;
};
 
module.exports = partition;