206_反转链表
206_反转链表
package 链表; /** * https://leetcode-cn.com/problems/reverse-linked-list/ * 递归: 根据语义 reverseList(ListNode head),返回一条倒置的链表的头结点, * 例如:原结点是 heda -》5-》4 -》3 -》2 -》1 * 利用语义的话 reverseList(head.next),得到了 head -》5 -》 * newHead -》1 -》2 -》3 -》4 * 细节:因为没有断链,原来的5 还是指导 4 身上, 即 newHead -》1 -》2 -》3 -》4 《- 5 《- head * 所以,我们可以通过 5 的关系,拿到 4,调整4 指向5 , * 细节, 5是最后一个结点:它的next 需要指向空, 通过 head的关系拿到 5 * @author Huangyujun * *递归思想:第一步搞懂函数的语义,然后调用自身函数,将会得到什么 */ public class _206_反转链表 { public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public ListNode reverseList(ListNode head) { // if(head == null) return null;//return head; 也一样 // if(head.next == null) return head; //考虑到 head.next 是否为空,为空说明当前只有一个结点,反转即本身 if(head == null || head.next == null) return head; ListNode newHead = reverseList(head.next); //细节:这里用的是head.next.next(就是 4 这个结点的next指针),而不用 newHead这个变量,好处不用判断newHead(不为空时,就是4 这个结点) 是否为空, //因为咱如果是使用 newHead.next = head;(5 这个结点) 之前必须判断 newHead 是否为空,而使用 head.next(代表4 这个结点) 时,就可以避免判断情况 head.next.next = head; head.next = null; return newHead; } //非递归实现 public ListNode reverseList2(ListNode head) { ListNode newHead = null; while(head != null) { ListNode tmp = head.next; head.next = newHead; newHead = head; head = tmp; } return newHead; } }
本文来自博客园,作者:一乐乐,转载请注明原文链接:https://www.cnblogs.com/shan333/p/15708928.html
浙公网安备 33010602011771号