数据结构-链表
Posted 渣渣辉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构-链表相关的知识,希望对你有一定的参考价值。
把数组转成链表
var head = [1, 2, 3, 4, 5]
function arrayToListNode(arr) {
if (arr.length === 0) return null;
let head = { val: arr[0], next: null }
let pre = head;
for (let i = 1; i < arr.length; i++) {
pre.next = { val: arr[i], next: null }
pre = pre.next
// let node = { val: arr[i], next: null }
// pre.next = node;
// pre = node
}
return head
}
head = arrayToListNode(head)
console.log(\'head\', head)
function arrToListNode (arr) {
let head = new ListNode()
let cur = head
for (let i = 0; i < arr.length; i++) {
let node = new ListNode(arr[i])
cur.next = node
cur = cur.next
}
return head.next
}
var arr = [1, 2, 3, 4]
var res = arrToListNode(arr)
console.log(\'res111\', res)
实例
61
var head = [1,2,3,4,5]
var head = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: {
val: 5,
next: null
}
}
}
}
}
链表中的浅拷贝
var head1 = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: {
val: 5,
next: null
}
}
}
}
}
var cur1 = head1;
while (cur1.next && cur1.val < 3) {
cur1 = cur1.next // 赋值不会触发
}
//1. 修改属性触发
cur1.next = null
//2. 修改属性触发
// cur1.next = cur1.next.next
console.log(\'head1\', head1);
console.log(\'cur1\', cur1);
等同于
var head1 = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: {
val: 5,
next: null
}
}
}
}
}
var cur1 = head1;
var cur2 = cur1;
cur2.next = null
console.log(\'head1\', head1);
console.log(\'cur1\', cur1);
console.log(\'cur2\', cur2);
以上是关于数据结构-链表的主要内容,如果未能解决你的问题,请参考以下文章
NC41 最长无重复子数组/NC133链表的奇偶重排/NC116把数字翻译成字符串/NC135 股票交易的最大收益/NC126换钱的最少货币数/NC45实现二叉树先序,中序和后序遍历(递归)(代码片段