206. Reverse Linked List java solutions
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
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) return null; 12 ListNode newlist = new ListNode(0); 13 while(head != null){ 14 ListNode tmp = new ListNode(head.val); 15 tmp.next = newlist.next; 16 newlist.next = tmp; 17 head = head.next; 18 } 19 return newlist.next; 20 } 21 }