每天一道题 day1 不管能不能做出来
题目:反转链表 II
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
code
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} left
* @param {number} right
* @return {ListNode}
*/
function getVals(head, left, right) {
const vals = []
//
const arr = []
let index = 0
for (let i = left; i <= right; i++) {
arr.push(i)
}
let hasVal = true
let node = head
while (hasVal) {
index++
if (arr.length && index === arr[0]) {
// node.val = listVal[0]
vals.push(node.val)
arr.shift()
}
if (!node.next) {
hasVal = false;
}
node = node.next
}
return vals.reverse()
}
var reverseBetween = function(head, left, right) {
const arr = []
let index = 0
for (let i = left; i <= right; i++) {
arr.push(i)
}
let listVal = getVals(head, left, right)
console.log(listVal)
let hasVal = true
let node = head
while (hasVal) {
index++
// 进入left
if (arr.length && index === arr[0]) {
node.val = listVal[0]
arr.shift()
listVal.shift()
}
if (!node.next) {
hasVal = false;
}
node = node.next
}
return head
};
费了老鼻子劲可算做出来了,还得理解一下什么是链表
// 链表的构造函数
function List(vals) {
this.val = vals[0]
if (vals.length) {
vals.shift()
this.next = new List(vals)
}
else {
this.next = null
}
}
上面优化的地方还有很多 时间关系下次优化
稍微优化了一下下
var reverseBetween = function (head, left, right) {
const arr = [];
for (let i = left; i <= right; i++) {
arr.push(i)
}
let index = 0
, hasVal = true
, node = head
, vals = []
, nodes = [];
while (hasVal) {
if (!node.next) {
hasVal = false;
}
index++
if (arr.length && index === arr[0]) {
arr.shift()
vals.push(node.val)
nodes.push(node)
}
if (!(arr.length) && vals.length) {
// 这里开始翻转
vals = vals.reverse();
nodes.forEach((n, key) => {
n.val = vals[key]
})
return head
}
node = node.next
}
return head
};