Reverse Linked List
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
{
return head;
}
ListNode current = head.next;
ListNode prev = head;
prev.next = null; // Make the original head the last node in the reversed list
while (current != null)
{
ListNode nextTemp = current.next; // Temporarily store the next node
current.next = prev; // Reverse the link
prev = current; // Move prev one step forward
current = nextTemp; // Move current one step forward
}
return prev; // Return the new head of the reversed list
}
}Last updated