首页 > 其他 > 详细

LeetCode 206.反转链表

时间:2020-07-15 11:18:43      阅读:45      评论:0      收藏:0      [点我收藏+]

反转一个单链表。

示例:

输入: 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;
    }
}

LeetCode 206.反转链表

原文:https://www.cnblogs.com/studywithme/p/13303693.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!