functionlistConstruct (arr) { let res = new Node(null) let cur = res arr.map(item => { cur.next = new Node(item) cur = cur.next }) return res.next }
插入元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functioninsertNode (list, value, pos) { let idx = 0 let res = new Node(0) res.next = list let cur = res while (idx < pos) { idx ++ cur = cur.next } let node = new Node(value) let temp = cur.next cur.next = node node.next = temp temp = null return res.next }
删除元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functiondeleteNode (list, pos) { let idx = 0 let res = new Node(0) res.next = list let cur = res while (idx < pos) { idx ++ cur = cur.next } let temp = cur.next cur.next = temp.next temp = null return res.next }
逆序构造
输入:[1, 2, 3, 4, 5, 6]
输出:6 -> 5 -> 4 -> 3 -> 2 -> 1
1 2 3 4 5 6 7 8 9 10
functionlistConstruct (arr) { let cur = null let pre = null arr.map(item => { cur = new Node(item) cur.next = pre pre = cur }) return pre }
链表反转
输入:1 -> 2 -> 3 -> 4 -> 5 -> 6
输出:6 -> 5 -> 4 -> 3 -> 2 -> 1
1 2 3 4 5 6 7 8 9 10 11
functionreverseList (list) { let cur = link let pre = null while (cur) { const temp = cur.next cur.next = pre pre = cur cur = temp } return pre }
循环链表
构造
输入:[1, 2, 3, 4, 5, 6]
输出:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 1
1 2 3 4 5 6 7 8 9 10
functionlistConstruct (arr) { let res = new Node(null) let cur = res arr.map(item => { cur.next = new Node(item) cur = cur.next }) cur.next = res.next // 将末尾指向头部 return res.next }
functionlistConstruct (arr) { let res = new Node(null) let cur = res arr.map((item, index) => { cur.next = new Node(item) cur.next.pre = index == 0 ? null : cur cur = cur.next }) return res.next }
插入元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functioninsertNode (list, value, pos) { let idx = 0 let res = new Node(0) res.next = list let cur = res while (idx < pos) { idx ++ cur = cur.next } let node = new Node(value) node.pre = cur node.next = cur.next cur.next.pre = node cur.next = node return res.next }
删除元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functiondeleteNode (list, pos) { let idx = 0 let res = new Node(0) res.next = list let cur = res while (idx < pos) { idx ++ cur = cur.next } cur.pre.next = cur.next cur.next.pre = cur.pre cur = null return res.next }