用javascript写一个链表反转的代码,将链表后半段进行反转。如果链表长2n,反转n+1到2n部分(n为正整数)。如果链表长2n+1,反转n+1到2n+1的部分。
时间: 2023-02-17 17:46:45 浏览: 113
js代码-5.3 反转部分链表
```
function reverseLinkedList(head) {
if (!head || !head.next) return head;
let prev = null;
let curr = head;
while (curr) {
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
```
这是反转整个链表的代码。要反转后半段,可以先使用快慢指针找到链表的中点,再将后半段反转,最后将反转后的后半段连接到前半段的末尾。
例如:
```
function reverseLinkedListInHalf(head) {
if (!head || !head.next) return head;
// Find the middle of the linked list
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half of the linked list
let prev = null;
let curr = slow;
while (curr) {
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// Connect the first half and the reversed second half
head.next = prev;
return head;
}
```
阅读全文