翻转链表
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
// 1 -> 2 -> 3 -> 4 -> 5
//prev = 1
// current = 2;
ListNode prev = head;
ListNode current = head.next;
// 1 2 -> 3 -> 4 -> 5
// prev = 1
// current = 2;
prev.next = null;
while (current != null) {
// First time
// Second time
// third time
// fourth time
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
//exit
//return prev = 5
return prev;
}
}
翻转链表(指定区域内链表翻转)
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || m >= n) {
return head;
}
ListNode dummy = new ListNode(-1);
//增加一个前置节点
dummy.next = head;
head = dummy;
//m 位置设置为head节点
for (int i = 1; i < m; i++) {
head = head.next;
}
ListNode prevM = head;
ListNode mNode = head.next;
ListNode nNode = mNode;
ListNode postN = nNode.next;
//区域内翻转
// nNode => prev;
//postN => current
for(int i = m; i < n; i++) {
ListNode next = postN.next;
postN.next = nNode;
nNode = postN;
postN = next;
}
//调整整个链表
mNode.next = postN;
prevM.next = nNode;
return dummy.next;
}
}



