反转
// 递归
ListNode reverse(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode newHead = reverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
// 迭代
ListNode reverse(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode ne = cur.next;
cur.next = pre;
pre = cur;
cur = ne;
}
return pre;
}
寻找链表中间节点
如果是奇数个节点,返回最中间的一个即可
如果是偶数个节点,返回中间靠右或靠左的那个。
//使用虚拟头节点,slow最终指向中间靠左的节点
if (head == null || head.next == null) return;
ListNode dummy = new ListNode(-1, head);
ListNode fast = dummy, slow = dummy;
do {
fast = fast.next.next;
slow = slow.next;
} while (fast != null && fast.next != null);
//不使用虚拟头节点,slow最终指向中间靠右的节点
if (head == null || head.next == null)
return head;
ListNode fast = head, slow = head;
do {
fast = fast.next.next;
slow = slow.next;
} while (fast != null && fast.next != null);
根据需求选择第一种或第二种写法!