Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Last active July 22, 2026 07:18
Show Gist options
  • Select an option

  • Save xgqfrms/a501cbd3badc256fce1fc862629c4b17 to your computer and use it in GitHub Desktop.

Select an option

Save xgqfrms/a501cbd3badc256fce1fc862629c4b17 to your computer and use it in GitHub Desktop.
LinkedListGenerator.js 链表生成器

linked-list

链表

https://leetcode.com/problem-list/linked-list/

11/82 Solved

class ListNode {
  constructor(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
  }
}



function LinkedListGenerator(arr) {
  let head;
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    if(i === 0) {
      head = new ListNode(arr[len - 1 - i], null);
    } else {
      let temp = new ListNode(arr[len - 1 - i], null);
      temp.next = head;
      head = temp;
    }
  }
  // console.log(head);
  return head;
}

LinkedListGenerator([1,2,3,4,5]);
@xgqfrms

xgqfrms commented Jul 22, 2026

Copy link
Copy Markdown
Author

@xgqfrms

xgqfrms commented Jul 22, 2026

Copy link
Copy Markdown
Author

tree

https://leetcode.com/problem-list/tree/

14/265 Solved

class treeNode {
  constructor(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
  }
}

// 生成二叉树
function generateBinarySearchTree(arr) {
  let root = new treeNode(arr[0]),
    curr = root,
    queue = new Array(),
    n = 0;
  queue.push(curr);
  while(queue.length > 0) {
    let size = queue.length;
    for(let i=0; i<size; i++) {
      curr = queue.pop();
      // L
      curr.left = arr[n+1] ? new treeNode(arr[n+1]) : null;
      // 如果是null就不入队
      curr.left && queue.unshift(curr.left);
      n++;
      // R
      curr.right = arr[n+1] ? new treeNode(arr[n+1]) : null;
        // 如果是null就不入队
      curr.right && queue.unshift(curr.right);
      n++;
    }
  }
  return root;
}

generateBinarySearchTree([1, 2, 3, 4, 5, 6, 7]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment