反转链表是必考题,必须要背下来。
对指针的进一步的深入了解
1.使用虚拟头结点的链表反转
关键点:新插入来的前后指向
// 方法1:虚拟结点法 public static ListNode reverseList(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 直接操作链表实现反转
1直接用局部变量节点记录
public ListNode reverseList(ListNode head ) { ListNode prev = null; ListNode curr = head; while (curr != null) { //保留下一个节点 ListNode next = curr.next; //执行反转 curr.next = prev; //更新前一个节点 prev = curr; //继续下一个节点 curr = next; } return prev; }
将上面这段代码在理解的基础上背下来,是的,因为这个算法太重要!!!!!
拓展 通过递归来实现反转
public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } //不断递归记录下一个 ListNode newHead = reverseList(head.next); //实现反转 head.next.next = head; //改变原来的链接 head.next = null; return newHead; }