Question
Reverse a singly linked list.
Solution 1 -- Iterative
Remember to set head.next = null or it will report "memory limit exceeds" error.
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 current = head, prev = head, post = head; 12 if (current == null || current.next == null) 13 return current; 14 current = current.next; 15 head.next = null; 16 while (current.next != null) { 17 post = current.next; 18 current.next = prev; 19 prev = current; 20 current = post; 21 } 22 current.next = prev; 23 return current; 24 } 25 }
Solution 2 -- Recursive
We can also use recursion to solve this problem.
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) 12 return head; 13 ListNode second = head.next; 14 head.next = null; 15 ListNode newHead = reverseList(second); 16 second.next = head; 17 return newHead; 18 } 19 }
时间: 2024-10-15 22:07:02