1.简历虚拟表头
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;
}
该文章介绍了如何使用Java编程语言实现链表的反转,包括:1)通过虚拟头节点;2)直接操作链表;3)递归方法。每种方法都提供了详细的代码实现。

被折叠的 条评论
为什么被折叠?



