合并两个有序链表
链表的特点:
无法直接获取第几个数/最后一个数
唯一的操作 .next
var mergeTwoLists = function(list1, list2) {
let curr = new ListNode();
let dummy = curr;//占住头部
// 进行比较
while( list1 !== null && list2 !== null){
if(list1.val < list2.val ){
curr.next = list1;
list1 = list1.next;
}else{
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;//移动指针
}
if(list1 !== null){
curr.next = list1;
}
if(list2 !== null){
curr.next = list2;
}
return dummy.next;
};
两两交换链表中的结果
大数相加
var addStrings = function(num1, num2) {
const numArr1 = num1.split('').reverse();
const numArr2 = num2.split('').reverse();
let temp = 0;
let index = 0;
const result = [];
while(numArr1.length > index || numArr2.length > index){
let item1 = numArr1.length > index ? numArr1[index] : 0;
let item2 = numArr2.length > index ? numArr2[index] : 0;
let res = Number(item1) + Number(item2) + temp;
temp = res > 9 ? 1: 0;
result.push(res % 10);
index++;
}
if(temp === 1){ result.push(1) }
return result.reverse().join('');
};