美文网首页
反转单链表

反转单链表

作者: cc4393c | 来源:发表于2019-11-22 21:52 被阅读0次

    Reverse a Linked List

    iterative way

    1       ->       2     ->     3    ->    null
    head          next
    
    1       <-       2     ->     3    ->    null
    prev          head         next
    
    1       <-       2     <-     3    ->    null
                   prev          head         next
    
    1       <-       2     <-     3        null
                                 prev        head        
    
    Node reverse(Node head) {
      if (head == null || head.next == null) {
        return head;
      }
    
      Node prev = null;
      while (head != null) {
        Node next = head.next;
        head.next = prev;
        prev = head;
        head = next;
      }
     
      return prev;
    }
    

    recursive way

    1    ->     2      ->    3    -> null
    head       next
    
    1    ->     2      <-    3
    head       next       newHead
    
    null    <-    1     <-     2    <-     3
                 head         next        newHead
    
    Node reverse(Node head) {
      if (head == null || head.next == null) {
        return head;
      }
    
      Node newHead = reverse(head.next);
      head.next.next = head.next;
      head.next = null;
    
      return newHead;
    }
    

    相关文章

      网友评论

          本文标题:反转单链表

          本文链接:https://www.haomeiwen.com/subject/atsqwctx.html