有一個單鏈表,無序,給定一個值,將鏈表中小於這個值的節點放置於鏈表前面,節點之間相對順序不變。
這個題目我是這樣想的,我們遍歷單鏈表,當遇到大於指定指的節點群后,再其后面查找小於指定值的節點群,然后交換兩個節點群的位置。
思路有了,大致的代碼:
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());
運行效果:
我上面的代碼簡化一個地方,將等於value的節點也規划成大於value的節前群中,這樣單鏈表中只會存在兩種類型的節點,大於和小於,因此上面代碼中,n3之后肯定是n4,如果需要將等於獨立出來,那么我們就再需要兩個變量來記錄等於value的節點群。