标签:code style 合并 题意 eth lis list ext var
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
题意:按照大小顺序合并两个链表
代码如下:
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { //判断两链表是否为空 if(!l1 || !l2) return l1===null?l2:l1; if(!l1 && !l2) return null; //创建新链表存储结果, let head; //创建指针分别沿着l1,l2遍历 let node1=l1,node2=l2; //比较l1,l2头结点,较小的赋给新链表 if(l1.val>l2.val){ head=l2; node2=node2.next; }else{ head=l1; node1=node1.next; } //创建指针沿着新链表移动 let node=head; //不断比较两链表对应节点,直到其中一链表到尾 while(node1 && node2){ if(node1.val>node2.val){ node.next=node2; node=node.next; node2=node2.next; }else{ node.next=node1; node=node.next; node1=node1.next; } } //判断两链表谁先到头 if(!node1 && !node2){ return head; } if(!node2&&node1){ node.next=node1; } if(!node1&& node2){ node.next=node2; } return head; };
21. Merge Two Sorted Lists(js)
标签:code style 合并 题意 eth lis list ext var
原文地址:https://www.cnblogs.com/xingguozhiming/p/10387366.html