206. Reverse Linked List

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



 

 

 

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode prev = null;
        ListNode next = null;
        ListNode cur = head;
        
        while (cur != null){
          next = cur.next;
          cur.next = prev;
          prev = cur;
          cur = next;
        }
        return prev;
    }
}

 

这个题看似简单, 也是基础题, 但是我觉得要考虑的东西挺多的, 需要记住大概是怎么做的, 写代码之前要走例子。 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    public ListNode reverseList(ListNode head) {
      if(head == null || head.next == null){
        return head;
      }
      
      ListNode prev = null;
      ListNode next = null;
      ListNode cur = head;
      
      while(cur!= null){
        next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
      }
      return prev;
    }
}

// 这个iterative 的方法要记住 initialize 三个 node. prev, cur, next. 步骤分别是, 保留 next, connect cur and prev,(reverse), 然后移动 prev and cur. 这里看起来没有写断链, 但其实上, 在cur.next = prev 时, 已经断链, 因为每个single linked node 每个node 只有一个next pointer。 把next 指向别人后, 已经不把next 指给别人了。 所以开始要保留 next node, 为了下次 reverse。 这个走个简单的例子, 比如 1-> 2 -> 3 把什么时候出loop, 最后一个节点是哪个,要返回什么

      



class Solution {
    public ListNode reverseList(ListNode head) {
      if(head == null || head.next == null){
        return head;    
      }
      
      ListNode p = reverseList(head.next);
      head.next.next = head;
      head.next = null;
      return p;
    }
}

      
//  这个的base case 很强。 如果head 是 null, return head = null。 如果 head 是一个节点(head.next == null), 那 return head。  它本身

// 一会到了recursion 的时候, 因为是最后一个节点, 所以 head.next = null. 这是返回 head 也就是 最后一个节点
// ListNode p = reverseList(head.next); recursion 回来的时候也是最后一个节点。 所以返回最后一个节点。 

// 中间的reverse 是: 1-> 2 -> 3 
//  head.next.next = head;   1.next.next = 1  1<- 2 
// 需要断链, 因为 1 还是 指向 2 。 所以 1.next = null。 这个 是 断 1-> 2 的链 。 然后 可能会担心1 的链指向 哪, 因为default 是 null, 所以是 null。 这个画图走一下就知道了

 

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

posted on 2018-07-18 09:10  猪猪&#128055;  阅读(100)  评论(0)    收藏  举报

导航