// 反转链表,每 k 个节点反转一次,不足 k 就保持原有顺序
// 构建链表
function list(...val) {
let obj = val.reverse().map((res, i) => Object.assign({}, { [i]: new Node(res) }));
for (let item in obj) {
if (item != 0) obj[item][item].next = obj[Number(item) - 1][Number(item) - 1]
}
return obj[obj.length - 1][obj.length - 1];
};
class Node {
constructor(element) {
this.value = element;
this.next = null;
}
}
// 链表反转
function reverse_linkedList(linkedList) {
let str = '';
let fn = function (list) {
if (n === 1) {
if (list.next && list.next.next) {
let value = list.value;
let endValue = list.next.next.value;
list.next.next.value = value;
list.value = endValue;
}
}
str += list.value.toString() + ">"
if (n === 3) {
n = 0
}
if (list.next === null) {
return false
};
n++
fn(list.next)
return str.substring(0, str.length - 1)
}
return fn.call(reverse_linkedList, linkedList, n = 1)
}
let linkedList = list(1, 2, 3, 4, 5, 6, 7, 8);
console.log("原始链表", list(1, 2, 3, 4, 5, 6, 7, 8));
reverse_linkedList(linkedList);
console.log("反转链表", linkedList);
反转链表,每 k 个节点反转一次,不足 k 就保持原有顺序
最新推荐文章于 2021-03-25 15:18:13 发布