function reverseBetween( head , m , n ) {
if(head === null || head.next === null || m === n) return head;
let newHead = new ListNode(-1);
newHead.next = head;
let p = newHead;
for(let i=1; i<m; i++){
p = p.next;
}
let pre = p.next;
let cur;
for(let i=0; i<n-m; i++){
cur = pre.next;
pre.next = pre.next.next
cur.next = p.next;
p.next = cur;
}
return newHead.next;
}
题目相关:
链表反转的方法
对于下图这样的简单链表进行反转
function reverse(head){}
一、头插法
1. 定义一个新的头节点
2. 依次将结点插入新头节点和第一个结点之间
function reverse(head){
if(head === null || head.next === null) return head;
let newHead = new ListNode(-1);
let pre = head;
let cur;
while(pre){
cur = pre;
pre = pre.next;
cur.next = newHead.next;
newHead.next = cur;
}
return newHead.next;
}
二、就地反转(三指针法)
1. 将当前结点指向前一结点(cur.next = pre)
2. 当前指针后移。为避免丢失后一节点指向,在上一步前应先储存cur.next的值
temp = cur.next;
cur.next = pre;
function reverse(head){
if(head === null || head.next === null) return head;
let cur = head;
let pre = null;
let temp = null;
while(cur){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
|