反转链表是最基本的算法题,很多和链表相关的题目都会涉及到。
题解:《剑指offer》系列 反转链表(Java)
LeetCode:92. 反转链表 II
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode pre = head;
ListNode p = head;
ListNode first = head, second = head;
int i = 1;
while (i <= n) {
if (i == m - 1) {
pre = p;
}
if (m == i) {
first = p;
}
if (n == i) {
second = p;
}
p = p.next;
i++;
}
reserve(first, second);
//说明前面翻转链表前没有节点
if (m == 1) {
first.next = p;
return second;
} else {
pre.next = second;
first.next = p;
return head;
}
}
public ListNode reserve(ListNode first, ListNode second) {
ListNode prev = null;
ListNode last = second.next;
while (first != last) {
ListNode next = first.next;
first.next = prev;
prev = first;
first = next;
}
return prev;
}
}
LeetCode:25. K 个一组翻转链表
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode p = head;
ListNode newHead = head;
ListNode result = head;
ListNode beforeLast = null;
int len = 1;
while (true) {
int i = 0;
while (i < k && p != null) {
p = p.next;
i++;
}
if (i < k) {
return result;
} else {
//一次遍历
ListNode q = reverse(newHead, k);
if (beforeLast != null) {
beforeLast.next = q;
}
if (len == 1) {
result = q;
}
len++;
ListNode temp = q;
int j = 1;
while (j < k) {
j++;
temp = temp.next;
}
temp.next = newHead = p;
beforeLast = temp;
}
}
}
//从当前结点开始 k个链表反转
private ListNode reverse(ListNode head, int k) {
ListNode p = null;
ListNode cur = head;
int i = 0;
while (i < k) {
ListNode temp = cur.next;
cur.next = p;
p = cur;
cur = temp;
i++;
}
return p;
}
}