206.Reverse Linked List
Reverse a singly linked list.
简单题目不简单,数据结构的基础,在不生成新链表的情况下原地生成一个反转链表。
var reverseList = (head) => {
let tail = head;
if (!head || !head.next) {
return head;
}
while (tail.next) {
let tmp = tail.next.next;
tail.next.next = head;
head = tail.next;
tail.next = tmp;
}
return head;
};
92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
上一题的扩展,只反转一部分链表,可以继续沿用上题的部分思想,通过一个depth来确认链表反传到了哪一层来跳出循环。
var reverseBetween = function (head, m, n) {
let curr = head;
let depth = 0;
let lastCurr;
for (let i = 0; i < m - 1; i++) {
lastCurr = curr;
curr = curr.next;
}
let tail = curr;
while (depth < n - m) {
let tmp = tail.next.next;
tail.next.next = curr;
curr = tail.next;
tail.next = tmp;
depth++;
}
lastCurr ? (lastCurr.next = curr) : head = curr;
return head;
};
25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
将链表分成长度为k的数段,反转每一段,只允许使用常量级别的额外空间。
var reverseKGroup = function (head, k) {
if (k === 1) {
return head;
}
let curr = head;
let headTail,tailHead,rowHead;
let count = 0;
while (curr) {
if (!rowHead) {
rowHead = curr;
curr = curr.next;
} else if ((count + 1) % k === 0) {
tailHead = curr.next;
curr.next = null;
let [kHead, kTail] = reverseinK(rowHead);
if (headTail) {
headTail.next = kHead;
kTail.next = tailHead;
headTail = kTail;
} else {
head = kHead;
headTail = kTail;
headTail.next = tailHead;
}
rowHead = null;
curr = tailHead;
} else {
curr = curr.next;
}
count++;
}
return head;
};
var reverseinK = function (head) {
let tail = head;
while (tail.next) {
let tmp = tail.next.next;
tail.next.next = head;
head = tail.next;
tail.next = tmp;
}
return [head, tail]
}