LeetCode:206 反转链表

100 阅读1分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战

题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表

示例 1:

img

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

img

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

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

解题

解题一:迭代

思路

代码

/**
 * Definition for singly-linked list.
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {

    public ListNode reverseList(ListNode head) {
        // 空链表 和 只有一个节点的链表 返回原本的链表
        if (head == null || head.next == null) {
            return head;
        }
        ListNode tempHead = head.next;
        ListNode tail = tempHead.next;
        head.next = null;
        tempHead.next = head;
        head = tempHead;
        while (tail != null) {
            tempHead = tail;
            tail = tail.next;
            tempHead.next = head;
            head = tempHead;
        }
        return head;
    }
}

  • 执行耗时:0 ms,击败了100.00% 的Java用户
  • 内存消耗:38 MB,击败了87.86% 的Java用户

解题二:递归

思路

递归进行

代码

/**
 * Definition for singly-linked list.
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {

    public ListNode reverseList(ListNode head) {
        return change(head);
    }

    public ListNode change(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode resultNode = change(head.next);
        head.next.next =head;
        head.next = null;
        return resultNode;
    }

}

总结

  • 执行耗时:0 ms,击败了 100.00% 的 Java 用户
  • 内存消耗:38.3 MB,击败了 31.51% 的 Java 用户