Tuesday, September 15, 2015

Reverse Linked List

Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution1: iteratively
Time complexity is O(n), constant space.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode p1 = head;
        ListNode p2 = head.next;
        head.next = null;
        while (p1 != null && p2 != null) {
            ListNode temp = p2.next;
            p2.next = p1;
            if (temp != null) {
                p1 = p2;
                p2 = temp;
            } else {
                break;
            }
        }
        
        return p2;
    }
}
Solution2: recursively
Time complexity is O(n), stack space.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode second = head.next;  
        head.next = null;  // 把每个node都打断
        
        ListNode rest = reverseList(second);
        second.next = head;  // 反向把node都连起来
        
        return rest;
    }
}

Reference: http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/

No comments:

Post a Comment