有序数组归并和有序单链表归并

学归并排序算法的时候,先要了解归并有序数组。

顺便写个有序单链表的归并

/*有序数组的归并*/
function mergeArr(arr1, arr2) {
	var result = [], 
		arr1_index = 0, 
		arr2_index = 0;
	while(arr1_index < arr1.length &&
		  arr2_index < arr2.length) {
		if(arr1[arr1_index] < arr2[arr2_index]) {
			result.push(arr1[arr1_index]);
			arr1_index++;
		} else {
			result.push(arr2[arr2_index]);
			arr2_index++;
		}
	}

	while(arr1_index < arr1.length) {
		result.push(arr1[arr1_index]);
		arr1_index++;
	}

	while(arr2_index < arr2.length) {
		result.push(arr2[arr2_index]);
		arr2_index++;
	}

	return result;
}


var arr1 = [1, 2, 4, 20, 30];
var arr2 = [0, 9];

//console.log(mergeArr(arr1, arr2));


/*有序单链表的归并*/
function LinkedList() {
	var Node = function (value) {
		this.value = value;
		this.next = null;
	}

	var head = null;
	var length =0;

	this.append = function (value) {
		var node = new Node(value);
		if(head == null) {
			head = node;
			length++;
			return;
		} else {
			appendNode(head, node);
		}
	}

	function appendNode(root, node) {
		if(root.next == null) {
			root.next = node;
		} else {
			appendNode(root.next, node);
		}
		length++;
	}

	this.toString = function () {
		var result = [];
		var temp = head;
		while(temp != null) {
			result.push(temp.value);
			temp = temp.next;
		}

		return result.join(" ");
	}

	this.getHead = function () {
		return head;
	}

	this.getLength = function () {
		return length;
	}
}


function linkedTest() {
	var arr1 = [2, 6, 9, 18, 25];
	var arr2 = [0, 10, 30];
	var linked_list1 = new LinkedList();
	var linked_list2 = new LinkedList();
	for(var i=0; i<arr1.length; ++i) {
		linked_list1.append(arr1[i]);
	}

	for(var i=0; i<arr2.length; ++i) {
		linked_list2.append(arr2[i]);
	}

	console.log("linked list1 ", linked_list1.toString());
	console.log("linked list2 ", linked_list2.toString());

	var merge_list = mergeLinkedList(linked_list1, linked_list2);
	console.log(merge_list.toString());
}


/*单链表合并*/
function mergeLinkedList(list1, list2) {
	var result_list = new LinkedList(),
		list1_node = list1.getHead();
		list2_node = list2.getHead();

	while(list1_node && list2_node) {
		if(list1_node.value < list2_node.value) {
			result_list.append(list1_node.value);
			list1_node = list1_node.next;
		} else {
			result_list.append(list2_node.value);
			list2_node = list2_node.next;
		}
	}

	while(list1_node) {
		result_list.append(list1_node.value);
		list1_node = list1_node.next;
	}

	while(list2_node) {
		result_list.append(list2_node.value);
		list2_node = list2_node.next;
	}

	return result_list;
}

linkedTest();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值