方法一:利用虚拟头节点
![](https://i-blog.csdnimg.cn/blog_migrate/435ce62bf633ffbb0a39ba4b0c727172.png)
// 链表反转 leetcode206 借助虚拟头节点
public static ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
ListNode ans = new ListNode(-1);
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = next;
}
// 返回的是 ans的下一个节点
return ans.next;
}
方法二:直接操作链表
// 直接操作链表
public static ListNode reverseList2(ListNode head){
if(head == null){
return null;
}
ListNode pre = null;
ListNode cur = head;
while(cur != null){
// next指针放在循环里 防止next = null 时还用 next = next.next
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
/*if(cur == null){
return pre;
}else{
next = cur.next;
}*/
}
return pre;
}