1.简历虚拟表头![](https://i-blog.csdnimg.cn/blog_migrate/dc54e29c4ae064b3ef5030221eb5a133.png)
public static ListNode reverseListByDummyNotCreate(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;
while (cur != null) {
cur.next = ans.next;
ans.next = cur;
cur = cur.next;
}
return ans.next;
}
2.直接操作链表实现反转
public static ListNode reverseListSimple(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
3.递归实现反转
注:图片仅为个人理解用,多画了条竖杠懒得擦了
public static ListNode reverseListByRecurse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseListByRecurse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}