本文阐述了用JS实现的合并两个有序链表的算法。分享给大家参考,如下:
将两个有序链表合并成一个新的有序链表并返回。新的链表由给定的两个链表的所有节点拼接而成。
示例:
输入:1-2-4,1-3-4输出:1-1-2-3-4-4
可以直接运行的程序:
scriptfunction Node(元素){ this.element=element//当前节点的元素是this,next=null;//下一个节点链接}函数列表(){这个。head=新节点(' head ');//head node this . find=find;//查找节点this.insert=insert//插入节点this.remove=remove//删除节点this.display=display//显示链表this . find previous=find previous;//查找上一个节点}//以下函数为操作方法:对应List类构造函数中的名称//查找给定节点functionfind(item){ var curr node=this . head;while(currNode.element!=item){ CurrNode=CurrNode . next;}返回currNode}//在链表中插入节点函数insert (newelement,item){ var new node=new node(new element);var current=this . find(item);if(current==null)返回console.log('找不到项目');new node . next=current . next;current.next=newNode}//删除节点函数remove (item) {var prev node=this。findprevious(项);if(prevNode.next!=null)prev node . next=prev node . next . next;}//从链表中删除一个节点时,我们首先需要找到要删除节点的上一个节点。找到它后,我们修改它的下一个属性,使它不指向要删除的节点,而是指向要删除的节点的下一个节点。然后,我们需要定义一个findPrevious方法来遍历链表,并检查每个节点的下一个节点是否存储了要删除的数据。如果找到,则返回该节点,以便可以修改其下一个属性。//用删除节点函数查找上一个节点查找上一个(项){var curr node=this。头部;while(currNode.next!=null currNode.next.element!=item){ CurrNode=CurrNode . next;}返回currNode}//显示链表元素function display(){ var current=this。头部;while(current.next!=null){ console . log(current . next . element);current=current.next} }/* * * @ param { node } L1 * @ param { node } L2 * @ return { node } */var mergetwolits=function(L2 L1){//模仿链表var mergedhead={element:-1,next: null}的数据结构,cur=while(L1 L2){ if(L1 . element=L2 . element){ cur . next=L1;l1=l1.next} else { cur.next=l2l2=l2.next} cur=cur.next} cur.next=l1 || l2返回mergedHead.next};让list1=新的List();list1.insert(1,' head ');list1.insert(2,1);list1.insert(4,2);console . log(list 1 . display());让list2=新的List();list2.insert(1,' head ');list2.insert(3,1);list2.insert(4,3);console . log(list 2 . display());console . log(mergetwolits(list 1 . head,list 2 . head))/脚本感兴趣的朋友可以使用在线的HTML/CSS/JavaScript代码来运行该工具:http://tools.jb51.net/code/HtmlJsRun测试了上面的代码,看看运行效果。
更多对JavaScript相关内容感兴趣的读者可以查看本网站专题:《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》和0103010
希望本文对JavaScript编程有所帮助。