当前位置: 代码迷 >> 综合 >> LeetCode 206 Reverse Linked List
  详细解决方案

LeetCode 206 Reverse Linked List

热度:116   发布时间:2023-10-28 04:39:36.0

递归实现

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

迭代实现

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

复杂度

时间复杂度O(n)
空间复杂度O(n)

  相关解决方案