Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Iteratively:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode reverseList(ListNode head) { 11 ListNode first = null; 12 ListNode second = head; 13 while(second != null){ 14 ListNode tmp = second.next; 15 second.next = first; 16 first = second; 17 second = tmp; 18 } 19 return first; 20 } 21 }
recursively:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode reverseList(ListNode head) { 11 if(head == null || head.next == null) return head; 12 ListNode nextNode = head.next; 13 head.next = null; 14 ListNode newHead = reverseList(nextNode); 15 nextNode.next = head; 16 return newHead; 17 } 18 }