链表之和
给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是十位数...),求这个两个数的和,结果也用链表表示。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ function addTwoNumbers( l1 , l2 ) { // write code here if(l1==null) {return l2} if(l2==null) {return l1} var newList = {} var head = newList var flag = false var cur1 = l1 var cur2 = l2 while(cur1&&cur2){ var num = cur1.val + cur2.val if(flag){ num += 1 flag = false } if(num>=10){ num %= 10 flag = true } var newNode = new ListNode(num) head.next = newNode head = head.next cur1 = cur1.next cur2 = cur2.next } while(cur1){ var num = cur1.val if(flag){ num +=1 flag = false } var newNode = new ListNode(num) head.next = newNode head = head.next cur1 = cur1.next } while(cur2){ var num = cur2.val if(flag){ num +=1 flag = false } var newNode = new ListNode(num) head.next = newNode head = head.next cur2 = cur2.next } if(flag){ var newNode = new ListNode(1) head.next = newNode } return newList.next } module.exports = { addTwoNumbers : addTwoNumbers };
链表算法 文章被收录于专栏
链表相关算法