Back to Dashboard
Reverse Linked List
EasyProblem Statement
Given the head of a Singly LinkedList, reverse the list, and return the head of the reversed list.
Examples
Example 1:
- Input:
head = [1,2,3,4,5] - Output:
[5,4,3,2,1]
Approach 1 Iterative:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
var temp = head;
while (temp != null) {
var front = temp.next;
temp.next = prev;
prev = temp;
temp = front;
}
return prev;
}
}