LeetCode每日一题:反转链表(No.206)

166 阅读2分钟

题目:反转链表


 反转一个单链表。

示例:


输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思考:


首先用递归来解决。
如果传入的节点(head)为null或该节点的next(head.next)为null,则返回该节点。
否则递归调用自身将下一个节点传入(head.next)。
再将当前方法中传入的节点和其后一个节点反转。

实现:


  public class Solution {
    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;
    }
}

理解:


①处两行代码完成了将传入的head节点与head.next反转。
②处首先判断传入的head节点以及下一个节点head.next是否null,为null就直接返回head节点。
通过不断的递归调用reverseList方法,直至传入的节点为链表尾节点时head.next才会为null,直接返回尾节点。
所以newHead节点即为原来链表尾节点,反转后的头节点。
如果传入的节点head.next不为null,就是说没到尾节点,就将head节点与head.next节点反转。
最终会从递归调用的最里层开始,将最后一个节点和倒数第二个节点反转,再将倒数第二个节点和倒数第三个节点反转...... 返回结果是newHead节点,就是新的头节点。

再思考:


首先用迭代法来解决。
用三个指针,head,p,q分别指向头节点,前一个节点和后一个节点。
然后循环每次反转p与q节点,反转后将q后移,一直到q为null即链表尾部位置。

实现:


public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = head;
        ListNode q = head.next;
        while (q != null) {
            p.next = q.next;
            q.next = head;
            head = q;
            q = p.next;
        }
        return head;
    }
}

理解:


如下图所示,主要是while循环中,用三个指针反转节点,每次反转后记得修改head的位置和将q向后移。最终head为反转后列表的头节点。