网站系统制作教程,WordPress1001无标题,怎么做二维码直接进入网站,cnetos 7 wordpress本文实例讲述了JS实现的合并两个有序链表算法。分享给大家供大家参考#xff0c;具体如下#xff1a;将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例#xff1a;输入#xff1a;1-2-4, 1-3-4输出具体如下将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例输入1-2-4, 1-3-4输出1-1-2-3-4-4可以直接运行的方案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类构造函数中的名称//查找给定节点function find(item) {var currNode this.head;while(currNode.element ! item) {currNode currNode.next;}return currNode;}//向链表插入一个节点function insert(newElement,item) {var newNode new Node(newElement);var current this.find(item);if(current null)return console.log(cant find the item);newNode.next current.next;current.next newNode;}//删除节点function remove(item) {var prevNode this.findPrevious(item);if(prevNode.next ! null)prevNode.next prevNode.next.next;}//从链表中删除节点时我们先要找个待删除节点的前一个节点找到后我们修改它的 next 属性使其不在指向待删除的节点而是待删除节点的下一个节点。那么我们就得需要定义一个 findPrevious 方法遍历链表检查每一个节点的下一个节点是否存储待删除的数据。如果找到返回该节点这样就可以修改它的 next 属性了。//查找带删除节点的前一个节点function findPrevious(item) {var currNode this.head;while(currNode.next ! null currNode.next.element ! item) {currNode currNode.next;}return currNode;}//显示链表元素function display() {var current this.head;while(current.next ! null) {console.log(current.next.element);current current.next;}}/*** param {Node} l1* param {Node} l2* return {Node}*/var mergeTwoLists function(l1, l2) {// 模仿链表的数据结构var mergedHead { element : -1, next : null },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 || l2return 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))感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具http://tools.jb51.net/code/HtmlJsRun测试上述代码查看运行效果。希望本文所述对大家JavaScript程序设计有所帮助。