建立虚拟结点辅助翻转
public ListNode reverseList(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = curNext;
}
return ans.next;
}
不带虚拟头结点翻转
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = pre;
pre = cur;
cur = curNext;
}
return pre;
}