xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Linked List & List Node All In One

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: '' } } }
*/

反转链表

https://leetcode.com/problems/reverse-linked-list/


/**
 * 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;
};

refs

https://www.educative.io/edpresso/what-is-a-linked-list

https://people.engr.ncsu.edu/efg/210/s99/Notes/LinkedList.1.html

PPT

https://www.slideshare.net/sshinchan/single-linked-list



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-11-17 17:55  xgqfrms  阅读(246)  评论(1编辑  收藏  举报