链表的定义和分类
单链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 自定义链表节点 function ListNode(val,next){ this.val = (val===undifined ? 0 : val) this.next = (next === undefined ? 0 : val) }
class ListNode{ val; next = null; constructor(value){ this.val = value; this.next = null } }
|
1 2 3 4 5 6 7 8
| class ListNode{ public val : number; public next : ListNode|null = null constructor(value:number){ this.val = value; this.next = null; } }
|
双链表
循环链表
链表相关题目
两数相加
https://leetcode.cn/problems/add-two-numbers/description/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| var addTwoNumbers = function(l1, l2) {
let res = new ListNode(0) let curr = res, p = l1, q = l2 let carry = 0 while(p != null || q != null){ let x = (p === null) ? 0 : p.val let y = (q === null) ? 0 : q.val let sum = x + y + carry carry = Math.floor(sum/10) curr.next = new ListNode(sum%10) curr = curr.next if (p != null) p = p.next if (q != null) q = q.next } if (carry > 0){ curr.next = new ListNode(carry) } return res.next };
|