JZ15-反转链表
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey
/** * 原地反转+尾插+不借助哨兵 较直观 */ public static ListNode reverseList21(ListNode head) { if (head == null) { return null; } ListNode pre = null;//前一个 ListNode pCut = head;//当前 while (pCut != null) { ListNode next = pCut.next; //记录下一个 pCut.next = pre;//前一个变成了当前的后一个。直接完成反转 c=a+b pre = pCut;//然后当前的变成了下一轮的前一个 b=c bc往后移一位 pCut = next;//下一轮,后面的变成当前的 a=b } return pre;//返回当前的前一个 } /** * 递归 太抽象 */ public static ListNode reverseList5(ListNode head) { if (head == null || head.next == null) { return head; } ListNode p = reverseList5(head.next);//整体思维,宏观语义 head.next.next = head;//我的下一个是我(反转)。。当成只有两个节点 head.next = null;//我的像一个为空。 1 2 null--》 2 1 null return p;//返回头节点 }