LeetCode 206.反转链表

反转一个单链表。

示例:

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

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

JavaScript题解:https://www.bilibili.com/video/BV1x7411i7Dd?p=1

力扣题解:https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/

迭代法:

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

        while(cur != null){
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}

递归法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //1.求解基本问题
        if(head == null || head.next == null){
            return head;
        }
        //2.将大问题划分为小问题
        ListNode res = reverseList(head.next);
        //3.小问题的解如何变为大问题的解
        head.next.next = head;
        head.next = null;
        return res;
    }
}
如果博客内容有误,请联系我修改指正,非常感谢! 如果觉得这篇博客对你有用的话,就帮我点个小小的赞吧! 一起加油鸭, 越努力,越幸运!!!
原文地址:https://www.cnblogs.com/studywithme/p/13303693.html