建立虚拟节点进行链表反转
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;
}
直接操作链表
public ListNode reverseList1(ListNode head){
ListNode prev = null;
ListNode cur = head;
while (cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}