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 reverseList2(ListNode head){
ListNode prev = null;
ListNode cur = head;
while (cur != null){
ListNode next = cur.next;//cur.next动了所以要存一下
cur.next = prev;
prev = cur;
cur =next;
}
return prev;
}
3.递归反转
public static ListNode reverseList3(ListNode head){
if (head == null||head.next == null) {
return head;
}
ListNode newHead = reverseList3(head.next);
head.next.next = head;
head.next = null;
return newHead;
}