链表反转
1. 建立虚拟头结点辅助反转
// 方法1:虚拟结点法
public static ListNode reverseList(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = next;
}
return ans.next;
}
2 直接操作链表实现反转
反转前后的结构和指针位置:
下图为执行期间的过程示意图,在图中,cur本来指向旧链表的首结点,pre表示已经调整好的新链表的表头,next是下一个要调整的。注意图中箭头方向,cur和pre是两个表的表头,移动过程中cur经过一次中间状态之后,又重新变成了两个链表的表头。
public 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;
}
这段代码重中之重
3 通过递归来实现反转
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}