1. 程式人生 > >206. Reverse Linked List - Easy

206. Reverse Linked List - Easy

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?

 

M1: iterative

需要兩個指標prev, cur。注意迴圈的終止條件是cur == null,否則最後一個節點和之前反轉完成的連結串列接不上,當cur = null的時候,返回prev即可。在每一次迴圈裡,先儲存cur的下一個節點nextnode,cur指向prev,prev向前移動,cur也向前移動,直到cur == null。

time: O(n), space: O(1)

/**
 * 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, cur = head; while(cur != null) { ListNode nextnode = cur.next; cur.next = prev; prev = cur; cur = nextnode; } return prev; } }

 

M2: recursive

base case是當head == null或者head.next == null時返回head. 用一個新的node表示對head.next呼叫函式的返回值. 當recursion到base case的時候,head到達了最後一個節點(head就是最後需要返回的值),此時把head的下一個節點指向head,head指向null,返回至上一層recursion.

e.g. 當recursion到base case,即head.next == null時,返回head,注意此時是對head.next呼叫recursive函式,即head.next.next == null返回,用cur儲存此時的返回值 (4),而head此時在3的位置。head.next.next = head操作後,4指向3,head.next = null操作後,3指向null (原來指向4)。再回上一層,head在2,兩步操作後,3->2;再回上一層,head在1,2->1。此時返回cur即可

1->2->3->4->null    1->2->3<-4   null

           h   c           h    c

1->2<-3<-4    null    1<-2<-3<-4   null

     h     c       h              c

time: O(n), space: O(n) - store the return value in each recursive call

/**
 * 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 cur = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return cur;
    }
}