Untitled
class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public class Solution { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode current = head; while (current != null) { ListNode next = current.next; // Save the next node current.next = prev; // Reverse the link prev = current; // Move prev one step forward current = next; // Move current one step forward } return prev; // prev becomes the new head } } public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; // Base case } ListNode newHead = reverseList(head.next); // Reverse the rest of the list head.next.next = head; // Make the next node point to current head.next = null; // Set the current node's next to null return newHead; // Return the new head of the reversed list } }
Leave a Comment