对中间的某个部分进行反转
- Runtime: 72 ms, faster than 81.19%
- Memory Usage: 37.2 MB, less than 5.25%
/**
* 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} m
* @param {number} n
* @return {ListNode}
*/
var reverseBetween = function(head, m, n) {
if(!head) return null
let prev = null
let cur = head
while (m > 1) {
prev = cur
cur = cur.next
m--
n--
}
let con = prev
let tail = cur
while(n > 0) {
let temp = cur.next
cur.next = prev
prev = cur
cur = temp
n--
}
tail.next = cur
if(con) {
con.next = prev
} else {
head = prev
}
return head
};
通过持续将下一个元素前置
- Runtime: 68 ms, faster than 91.86%
- Memory Usage: 37.1 MB, less than 14.29%
var reverseBetween = function(head, m, n) {
if(!head) return null
let prev = null
let cur = head
while(m > 1) {
prev = cur
cur = cur.next
m--
n--
}
let tempnext = null
while(n > 1) {
tempnext = cur.next
cur.next = tempnext.next
if(prev) {
tempnext.next = prev.next
prev.next = tempnext
} else {
tempnext.next = head
head = tempnext
}
n--
}
if(!prev && tempnext) {
head = tempnext
}
return head
};
网友评论