Linked List & List Node All In One 链表 & 节点 1. 单链表 2. 双链表 3. 环形链表 / 循环链表
链表 & 节点
链表类型
- 单链表
- 双链表
- 环形链表 / 循环链表
Singly Linked List (Uni-directional)
Doubly Linked List (Bi-directional)
Circular Linked List
js 实现 Linked List
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-11-17
* @modified
*
* @description 链表 & 节点
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
// 节点
function ListNode(val, next) {
this.val = 0 || val;
this.next = null || next;
}
// 链表
function LinkedList(value) {
const node = new ListNode(value, ``);
if(!head) {
head = node;
} else {
let current = head;
while(current.next) {
current = current.next;
}
current.next = node;
}
};
function LinkedList () {
// init & 闭包 closure
let length = 0;
let head = null;
// methods
this.append = function(value) {
const node = new ListNode(value, ``);
if(!head) {
head = node;
} else {
let current = head;
while(current.next) {
current = current.next;
}
current.next = node;
}
// log(`head =\n`, head)
length += 1;
}
this.getList = function() {
// log(`head =`, head)
return head;
}
}
const test = new LinkedList();
test.append(1);
test.append(2);
// test.append(3);
reverseList(test.getList())
/*
head = ListNode { val: 1, next: ListNode { val: 2, next: ListNode { val: 3, next: '' } } }
*/
反转链表
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let [prev, curr] = [null, head];
while (curr) {
let tmp = curr.next; // 1. 临时存储当前指针后续内容
curr.next = prev; // 2. 反转链表
prev = curr; // 3. 接收反转结果
curr = tmp; // 4. 接回临时存储的后续内容
}
return prev;
};
var reverseList = function(head) {
let [prev, curr] = [null, head];
while (curr) {
// swap
[curr.next, prev, curr] = [prev, curr, curr.next];
}
return prev;
};