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.直接操作链表实现反转
public static 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;
}