递归
反转链表
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
反转链表II
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1, head);
ListNode p = dummy;
for (int i = 0; i < left - 1; i++) {
p = p.next;
}
ListNode result = reverseN(p.next, right - left + 1);
p.next.next = back;
p.next = result;
return dummy.next;
}
public ListNode reverseN(ListNode head, int n) {
if (n == 1) {
back = head.next;
return head;
}
ListNode p = reverseN(head.next, n - 1);
head.next.next = head;
head.next = null;
return p;
}
K个一组翻转链表
class Solution {
private ListNode back;
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
ListNode p = head;
for (int i = 0; i < k; i++) {
if (p == null) {
return head;
}
p = p.next;
}
ListNode newHead = reverseK(head, k);
head.next = reverseKGroup(p, k);
return newHead;
}
public ListNode reverseK(ListNode node, int k) {
if (k == 1) {
back = node.next;
return node;
}
ListNode head = reverseK(node.next, k - 1);
node.next.next = node;
return head;
}
}
迭代
反转链表
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head, nxt;
while (cur != null) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
反转链表II
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1, head);
ListNode p = dummy;
for (int i = 0; i < left - 1; i++) {
p = p.next;
}
ListNode[] result = reverseN(p.next, right - left + 1);
p.next.next = result[1];
p.next = result[0];
return dummy.next;
}
public ListNode[] reverseN(ListNode head, int n) {
ListNode pre = null, cur = head, nxt = null;
for (int i = 0; i < n; i++) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return new ListNode[]{pre, nxt};
}
K个一组翻转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy, start = dummy.next, end = dummy.next;
int n;
while (end != null) {
n = 0;
start = pre.next;
while (end != null && n < k) {
end = end.next;
n++;
}
if (n < k) {
break;
}
ListNode[] res = reverseK(start, end);
pre.next.next = res[1];
pre.next = res[0];
pre = start;
}
return dummy.next;
}
public ListNode[] reverseK(ListNode start, ListNode end) {
ListNode pre = null, cur = start, nxt = null;
while (cur != end) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return new ListNode[]{pre, nxt};
}
}