虚拟结点法
用temp提前记录下一个要反转的结点
public static ListNode reverseList(ListNode head){
ListNode ans= new ListNode(-1);
ListNode cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = temp;
}
return ans.next;
}
不用虚拟头结点
使用三个指针,cur,prev,next。返回的是prev。
public static ListNode reverseList(ListNode head){
ListNode prev=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
拓展
递归
public static 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 nexHead;
}