const a = { value: 'a' };
const b = { value: 'b' };
const c = { value: 'c' };
const d = { value: 'd' };
// 创建链表
a.next = b;
b.next = c;
c.next = d;
// 遍历链表
let p = a; // 指针,指向 a
while (p) {
console.log(p.value);
p = p.next
}
const a = { value: 'a' };
const b = { value: 'b' };
const c = { value: 'c' };
const d = { value: 'd' };
// 创建链表,操作完之后的 a 相当于整条链表
a.next = b;
b.next = c;
c.next = d;
// 遍历链表
let p = a; // 指针,指向 a
while (p) {
console.log(p.value);
p = p.next
}
// 插入值
const e = { value: 'e' };
c.next = e;
e.next = d
// 删除
c.next = d; // e 被删除
// 新建 JSON 对象
const json = {
a: { b: { c: 1 } },
d: { e: 2 }
};
// 创建一条路径,求这条 json 沿着这条路径下的属性值为多少
const path = ['a', 'b', 'c'];
// 创建指针,指向 json
let p = json;
path.forEach(k => {
p = p[k];
});
console.log(p); // 1
__proto__
属性连接各种原型对象const obj = {};
const func = () => {};
const arr = [];
// 以下结果都是 true
console.log(obj.__proto__ === Object.prototype);
console.log(obj.__proto__.__proto__ === null);
console.log(func.__proto__ === Function.prototype);
console.log(func.__proto__.__proto__ === Object.prototype);
console.log(func.__proto__.__proto__.__proto__ === null);
console.log(arr.__proto__ === Array.prototype);
console.log(arr.__proto__.__proto__ === Object.prototype);
console.log(arr.__proto__.__proto__.__proto__ === null);
const obj = {};
Object.prototype.x = 'x';
console.log(obj.x); // x
// 验证 A 是否 instanceof B
const instanceOf = (A, B) => {
let p = A; // 指针 p
while (p) {
if (p === B.prototype) {
return true;
}
p = p.__proto__;
}
return false;
};
var foo = {},
F = function () {};
Object.prototype.a = 'value a';
Function.prototype.b = 'value b';
console.log(foo.a); // value a
console.log(foo.b); // undefined
console.log(F.a); // value a
console.log(F.b); // value b
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
解题步骤:
答案:
/**
* 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}
*/
var reverseList = function(head) {
let p1 = head; // 指向头节点
let p2 = null;
while (p1) {
const temp = p1.next;
p1.next = p2;
p2 = p1;
p1 = temp;
}
return p2;
};