1.建立虚拟节点辅助反转
第一次循环:
ListNode ans = new ListNode(-1);//创建虚拟头节点,简化代码
ListNode cur = head;//将传入的链表赋给cur
ListNode next = cur.next;//next即还未处理的链表
cur.next = ans.next;//第一次循环的时候,ans.next = null
ans.next = cur;
cur = next;
第二次循环:
ListNode next = cur.next;
cur.next = ans.next;//第二次循环的时候ans.next = 4
ans.next = cur;
cur = next;
…依次循环,当cur为空时,返回ans链表,即为反转之后的链表
下面为完整代码:
public static ListNode reverseListByDummyNotCreate(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = next;
}
return ans.next;
}
2.直接操作链表进行反转
与创建虚拟节点相比,直接操作链表的方法是在开始的时候创建prev指针代替虚拟节点
在代码的体现上ans.next = prev;
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.利用递归进行反转(拓展)
递归:
1. 函数要实现的功能->反转链表
public static ListNode reverseListByRecurse(ListNode head) {
}
2. 递归的循环结束条件->当链表为空表或者只有一个节点返回head
public static ListNode reverseListByRecurse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
}
3. 函数的等价关系式->将子链表先反转
ListNode newHead = reverseListByRecurse(head.next);
这个时候head为4->3
head.next.next = head;
head.next.next = head变成4->3->4->3->4->3……
head.next = null;
完整代码如下:
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;
}