Reverse a singly linked list.

Hint:

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

**Iterative solution:**/** * 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 prev = null; ListNode curr = head; ListNode next = head.next; while (curr != null) { curr.next = prev; prev = curr; curr = next; if (next != null) { next = next.next; } } return prev; } }

**Recursive solution:**/** * 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 next = head.next; ListNode newHead = reverseList(next); next.next = head; head.next = null; return newHead; } }

**Update on 11/6/15:****Recursive solution using two pointers:**/** * 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; } return reverseListHelper(null, head); } private ListNode reverseListHelper(ListNode prev, ListNode curr) { if (curr == null) { return prev; } ListNode newHead = reverseListHelper(curr, curr.next); curr.next = prev; return newHead; } }

## No comments:

## Post a Comment