1. 全链表反转
public static ListNode reverseIteratively(ListNode head) {
ListNode prev = null;
while(head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public static ListNode reverseRecursively(ListNode head) {
if(head == null || head.next == null) {
return head;
}else {
ListNode newHead = reverseRecursively(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
2. 链表区间反转
public static void intervalReverse(ListNode nodeLeft, ListNode nodeRight) {
if(nodeLeft == nodeRight) {
return;
}else{
ListNode last = nodeLeft.next;
ListNode cur = last.next;
while(cur != nodeRight) {
last.next = cur.next;
cur.next = nodeLeft.next;
nodeLeft.next = cur;
cur = last.next;
}
}
}