尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 298
已运行时间: 991
目录
  1. 148. 排序链表
  2. js 初始化单链表

尼采般地抒情

尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 298
已运行时间: 991

148. 排序链表

/**

- 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 sortList = function(head) {
  if (head === null) return head
  let arr = []
  while (head !== null) {
  arr.push(head.val)
  head = head.next
  }
  let result = arr.sort((a, b) => {return a - b})
  let result_head = new ListNode(result[0], null)
  let test = result_head
  result.forEach((data, index) => {
  if (index !== 0) {
  let temp = new ListNode(data,null)
  test.next = temp
  test = temp
  }
  })
  return result_head
  };

js 初始化单链表

// 节点
  class Node {
  constructor(value) {
  this.val = value
  this.next = null
  }
  }

// 利用数组来初始化单链表
class NodeList {
constructor(arr) {
let head = new Node(arr.shift())
let next = head
arr.forEach(data => {
next.next = new Node(data)
next = next.next
})
return head
}
}

let test = new NodeList([1, 2, 3, 4])
while (test !== null) {
console.log(test.val)
test = test.next
}

评论区

Twikoo giscus