Skip to content

Latest commit

 

History

History
81 lines (60 loc) · 1.32 KB

206.md

File metadata and controls

81 lines (60 loc) · 1.32 KB

206. 反转链表

题目描述

反转一个单链表。

示例

示例 1:

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

Code

Solution1

迭代的方式

/**
 * 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 = null;
        while (cur != null){
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}

Solution2

递归

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

题解

递归法视频:https://www.bilibili.com/video/av64065962?from=search&seid=14314062402167617559

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