面試題 - 無序單鏈表,排序

有一個單鏈表,無序,給定一個值,將鏈表中小於這個值的節點放置於鏈表前面,節點之間相對順序不變。javascript

這個題目我是這樣想的,咱們遍歷單鏈表,當遇到大於指定指的節點羣后,再其後面查找小於指定值的節點羣,而後交換兩個節點羣的位置。java

思路有了,大體的代碼:this

function LinkNode(data){
	this.data = data;
	this.next = null;
}

function LinkList(data){
	this.head = new LinkNode(data);
}
LinkList.prototype = {
	insert: function(data){
		var n = new LinkNode(data);
		var cur = this.head;
		while(cur.next != null){
			cur = cur.next;
		}
		cur.next = n;
	},
	toString: function(){
		var ret = [];
		var cur = this.head;
		while(cur != null){
			ret.push(cur.data);
			cur = cur.next;
		}
		return "LinkList: " + ret.join(" -> ");
	}
}

function test(list, v){
	var n1,n2,n3,n4,n5,cur;
	cur=list.head;
	while(cur != null){
		if(cur.data>=v){
			n2 = cur;
			n3 = cur;
			while(n3.next != null && n3.next.data >= v){
				n3 = n3.next;
			}
			n4 = n3.next;
			n5 = n3.next;
			while(n5!=null && n5.next != null && n5.next.data < v){
				n5 = n5.next;
			}
			if(n4 == null){
				return;
			}
			//
			if(n1 == null){
				list.head = n4;
			}else{
				n1.next = n4;
			}
			var c = n5.next;
			n5.next = n2;
			n3.next = c;
			cur = n4;
		}
		n1 = cur;
		cur = cur.next;
	}
}
var a = new LinkList(3);
a.insert(8);
a.insert(7);
a.insert(6);
a.insert(5);
a.insert(4);
a.insert(9);
a.insert(3);
a.insert(2);
a.insert(7);
a.insert(1);
console.log(a.toString());
test(a, 5);
console.log(a.toString());

 運行效果:prototype

 

我上面的代碼簡化一個地方,將等於value的節點也規劃成大於value的節前羣中,這樣單鏈表中只會存在兩種類型的節點,大於和小於,所以上面代碼中,n3以後確定是n4,若是須要將等於獨立出來,那麼咱們就再須要兩個變量來記錄等於value的節點羣。blog

相關文章
相關標籤/搜索