【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
function Node(element) {
this.element = element;
this.next = null;
}
function List() {
// this.head = new Node('Head');
// this.find = find;
// this.insert = insert;
// this.remove = remove;
// this.display = display;
// this.findPrevious = findPrevious;
}
List.prototype = {
head:new Node('Head'),
find:find,
insert:insert,
remove:remove,
display:display,
findPrevious:findPrevious
}
List.prototype.constructor = List;
function find(item) {
var currentNode = this.head;
while(currentNode.element != item) {
currentNode = currentNode.next;
}
return currentNode;
}
function insert(newElement,item) {
var newNode = new Node(newElement);
var currentNode = this.find(item);
if(currentNode == null) {
return console.log("can not find element")
}
newNode.next = currentNode.next;
currentNode.next = newNode;
}
function remove(item) {
var preNode = this.findPrevious(item);
if(preNode.next != null) {
preNode.next = preNode.next.next;
}
}
function findPrevious(item) {
var currentNode = this.head;
while (currentNode.next != null && currentNode.next.element != item) {
currentNode = currentNode.next;
}
return currentNode;
}
function display() {
var current = this.head;
while(current.next != null) {
console.log(current.next.element);
current = current.next;
}
}
var mergeTwoLists = function (l1, l2) {
var mergedHead = {element: -1, next: null};
var cur = mergedHead;
while (l1 && l2) {
if (l1.element <= l2.element) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 || l2;
return mergedHead.next;
}
let list1 = new List();
list1.insert(1,'Head');
list1.insert(2,1);
list1.insert(4,2);
console.log(list1.display());
let list2 = new List();
list2.insert(1,'Head');
list2.insert(3,1);
list2.insert(4,3);
console.log(list2.display());
console.log(mergeTwoLists(list1.head,list2.head))
来源:oschina
链接:https://my.oschina.net/u/2285087/blog/3143722