206. Reverse Linked List

题目

原始地址:https://leetcode.com/problems/reverse-linked-list/#/description

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        
    }
}

描述

翻转单链表,尽量使用循环和递归两种方式

分析

循环方式很简单,不赘述。
递归的话,因为最终返回的是翻转后链表的头节点,拿不到翻转后链表的尾节点就没有办法把当前节点接到后面。因此我们先用一个指针将next节点保存起来,当后面的部分翻转完成后,这个指针就会成为新链表的尾节点,将它指向当前节点即可。需要注意第15行要把当前节点的next置空,否则会出现节点循环引用的情况。

解法1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode p1 = null, p2 = head, p3;
        while (p2 != null) {
            p3 = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = p3;
        }
        return p1;
    }
}

解法2

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode next = head.next;
        head.next = null;
        ListNode newHead = reverseList(next);
        next.next = head;
        return newHead;
    }
}
posted @ 2017-05-02 19:48  北冥尝有鱼  阅读(82)  评论(0编辑  收藏  举报