合并两个有序链表(创建新链表往里面添加节点)
将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ function mergeTwoLists( l1 , l2 ) { // write code here if(l1 == null) { return l2 } if(l2 == null) { return l1 } var head={} var current = head while(l1&&l2){ if(l1.val<l2.val){ current.next = l1 current = current.next l1 = l1.next }else{ current.next = l2 current = current.next l2 = l2.next } } while(l1){ current.next =l1 current = current.next l1=l1.next } while(l2){ current.next =l2 current = current.next l2=l2.next } return head.next } module.exports = { mergeTwoLists : mergeTwoLists };
链表算法 文章被收录于专栏
链表相关算法