206. 反转链表 - 力扣(LeetCode)
1.建立虚拟头节点辅助反转
![](https://img-blog.csdnimg.cn/ac87e3dc910b47f7b37501b261c15971.png)
class Solution {
public ListNode reverseList(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;//定义cur为待处理链表的表头节点
while (cur != null) {
ListNode next = cur.next;//这里定义的next作循环里cur的遍历用,保留cur后面链表的信息。否则下一行代码断开后原链表就找不到了
cur.next = ans.next;//断开cur与余下链表的连接,接新链表的后面
ans.next = cur;//接虚拟头节点
cur = next;//遍历用,不直接cur = cur.next
}
return ans.next;
//虚拟头节点反转很简单,需要注意处理原链表不断变化的表头的身前身后即可
}
2.直接操作反转
![](https://img-blog.csdnimg.cn/afc493336664473d8cb5a614f394a5f3.png)
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode prev = bull;
while(cur!=null)
{
ListNode next = cur.next;//保留信息
cur.next = prev;//调转箭头,构造新链表
prev = cur;//更新prev
cur = next;//更新旧链表表头
}
return prev;
}
}
3.递归
![](https://img-blog.csdnimg.cn/0deeae21ff8a45048f65d683e6e85ec5.png)