206. Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Subscribe to see which companies asked this question
Hide Similar Problems
Iteratively:
/** * 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 a = head; ListNode b = head.next; while(b!=null) { ListNode bn = b.next; b.next = a; a = b; b = bn; } head.next = null; return a; } }
Recursively:

浙公网安备 33010602011771号