- 206.反转链表
- 21.合并两个有序链表
- 2.两数相加
206. 反转链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// 思路
// 通过改变cur的next值来完成链表的反转
// 缓存next
// 当前的next等于前一个
// 前一个等于当前
// 当前等于缓存next
var reverseList = function (head) {
let pre = null;
let temp = null;
let cur = head;
while (cur) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
};
// 输入:head = [1,2,3,4,5]
// 输出:[5,4,3,2,1]
21. 合并两个有序链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
// 链表理解起来还是有点困难的
var mergeTwoLists = function (list1, list2) {
if (list1 === null) return list2;
if (list2 === null) return list1;
if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list2.next, list1);
return list2;
}
};
2. 两数相加
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
// 思路
// 链表还是有点抽象的
var addTwoNumbers = function (l1, l2) {
let sbnode = new ListNode();
let cur = sbnode;
let carry = 0;
while (l1 || l2 || carry) {
if (l1) carry += l1.val;
if (l2) carry += l2.val;
cur = cur.next = new ListNode(carry % 10);
carry = Math.floor(carry / 10);
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return sbnode.next;
};
// 输入:l1 = [2,4,3], l2 = [5,6,4]
// 输出:[7,0,8]
// 解释:342 + 465 = 807.