单链表逆置(递归和迭代)

2022-02-25 08:43:15 浏览数 (1)

迭代

代码语言:javascript复制
class Solution {
  public ListNode reverseList(ListNode head) {
    if (head == null) return head;
    ListNode a=head, b=head.next;
    head.next = null;
    while (b != null) {
      ListNode c = b.next;
      b.next = a;
      a = b;
      b = c;
    }
    return a;
  }
}

递归

代码语言:javascript复制
class Solution {
  public ListNode reverseList(ListNode head) {
    if (head==null || head.next==null) {
      return head;
    }
    ListNode res = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return res;
  }
}

0 人点赞