zoukankan      html  css  js  c++  java
  • LC_206. Reverse Linked List

    https://leetcode.com/problems/reverse-linked-list/description/
    Hint:
    A linked list can be reversed either iteratively or recursively. Could you implement both?
    test case: 3->1->2>5 to 5->2->1->3
    x c
     1 public class LC206_ReverseLinkedList {
     2     public ListNode reverseLinkedList(ListNode head){
     3         if (head == null || head.next == null) return head ;
     4         ListNode prev = null, curr= head, next = null ;
     5         /*
     6         * 细节, 如果 写成curr.next != null, curr 会在 NODE4 但是没有进入循环,所以并不会连上前面的点,
     7         * 所以返回的时候会是一个单点,而不是链表
     8         * thats the reason curr should be stopped at null to make sure all prev nodes linked.
     9         * */
    10         while (curr != null ){
    11             next = curr.next ;
    12             curr.next = prev ;
    13             prev = curr ;
    14             curr = next ;
    15         }
    16         return prev ;
    17     }
    18 
    19     public ListNode reverseLinkedList2(ListNode head){
    20         //base
          if (head == null || head.next == null) return head ;
    21 /* 22 * 1-2-3-4 null<-1<-2<-3<-4 23 * current iteration head =2 expect null<-3<-4 24 * 25 * */ 26 ListNode newHead = reverseLinkedList2(head.next) ; 27 ListNode tail = head.next ; //3 28 tail.next = head ; //2<-3<-4 29 head.next = null; //null<-2<-3<-4 30 return newHead ; 31 } 32 }

    recursive:   assume Node2 is the head,  subproblem return:

                    null<-Node3 <- Node4  

    then you want to change to

    ListNode newHead = reverse(head.next) will generate the following pic: 

    ListNode tail = head.next ;  here tail is Node 3

    note here since we didnt touch head, thats the reason node2 still points to node3

    tail.next = head

     

    head.next = null;   //this is what you need to return for the upper level recursive

    因为这里是recursive, 一层层走下去 reverse(head.next) 所以base case:

    if(head == null || head.next == null) 最后head 会是 原 linkedlist 的尾巴,也就是新头。

  • 相关阅读:
    Flutter & Dart 安装在window系统
    HAWQ配置之客户端访问
    HAWQ配置之HDFS HA
    HAWQ集成Yarn HA作为资源管理服务
    ambari 安装HDP3.0.1后,启动服务的问题记录
    【Clojure 基本知识】小技巧s
    [转帖]Loading Data into HAWQ
    【Clojure 基本知识】 关于函数参数的各种高级用法
    【Clojure 基本知识】 ns宏的 指令(关键字) requrie的用法
    Linux系统解析域名的先后顺序【转帖】
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8456363.html
Copyright © 2011-2022 走看看