Friday, August 21, 2015

Reverse Linked List | Leetcode

Reverse a singly linked list.


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

---

Solution: Iterate through the list, getting the next node to point to the previous node.
/**
 * 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) {
        ListNode last = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = last;
            last = head;
            head = next;
        }
        return last;
    }
}

No comments: