public class ReverseListBetween {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
ListNode nodeA = initLinkedList(a);
ListNode d = null;
int testMethod = 1;
switch (testMethod) {
case 1://方法1:穿针引线法
d = reverseBetween(nodeA, 2, 4);
break;
case 2://方法2:头插法
d = reverseBetween2(nodeA, 2, 4);
break;
}
System.out.println(toString(d));
}
/**
* 方法1:穿针引线法
*
* @param head
* @param left
* @param right
* @return
*/
public static ListNode reverseBetween(ListNode head, int left, int right) {
// 因为头节点有可能发生变化,使用虚拟头节点可以避免复杂的分类讨论
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
// 第 1 步:从虚拟头节点走 left - 1 步,来到 left 节点的前一个节点
// 建议写在 for 循环里,语义清晰
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
// 第 2 步:从 pre 再走 right - left + 1 步,来到 right 节点
ListNode rightNode = pre;
for (int i = 0; i < right - left + 1; i++) {
rightNode = rightNode.next;
}
// 第 3 步:切断出一个子链表(截取链表)
ListNode leftNode = pre.next;
ListNode succ = rightNode.next;
// 注意:切断链接
pre.next = null;
rightNode.next = null;
// 第 4 步:同第 206 题,反转链表的子区间
reverseList(leftNode);
// 第 5 步:接回到原来的链表中
pre.next = rightNode;
leftNode.next = succ;
return dummyNode.next;
}
/**
* 基本的反转方法
*
* @param head
* @return
*/
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
/**
* 方法2:头插法
*
* @param head
* @param left
* @param right
* @return
*/
public static ListNode reverseBetween2(ListNode head, int left, int right) {
// 设置 dummyNode 是这一类问题的一般做法
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
ListNode cur = pre.next;
ListNode next;
for (int i = 0; i < right - left; i++) {
next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummyNode.next;
}
/**
* 初始化链表
*
* @param array
* @return
*/
private static ListNode initLinkedList(int[] array) {
ListNode head = null, cur = null;
for (int i = 0; i < array.length; i++) {
ListNode newNode = new ListNode(array[i]);
newNode.next = null;
if (i == 0) {
head = newNode;
cur = head;
} else {
cur.next = newNode;
cur = newNode;
}
}
return head;
}
/**
* 输出链表
*
* @param head 头节点
*/
public static String toString(ListNode head) {
ListNode current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.val).append("\t");
current = current.next;
}
return sb.toString();
}
static class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}
第一种是头插法本质是借助虚拟结点,第二种是穿针引线法本质是使用四个指针,
核心代码是链表反转代码
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}