Tuesday, July 21, 2015

Reverse LinkedList -- Leetcode

Question:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Answer:
1. Iteratively: (C++)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *prev = NULL, *cur = head, *next = NULL;
        while(cur){
            next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
};

2. Recursively: (Java)
/**
 * 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) {
        return recursive(head);
    }
    ListNode recursive(ListNode head) {
if (head == null)
return null;

        ListNode rest = head.next;   //next node of head
        if(rest == null){
            return head;             //where newHead returns in fact!
        }

ListNode newHead = recursive(head.next);
head.next.next = head;
head.next = null;

return newHead;
}

}


No comments:

Post a Comment