File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class ListNode {
2+ int val ;
3+ ListNode next ;
4+
5+ ListNode (int val ) {
6+ this .val = val ;
7+ }
8+ }
9+
10+ public class ReverseLinkedList {
11+ public ListNode reverseList (ListNode head ) {
12+ ListNode prev = null ;
13+ ListNode current = head ;
14+
15+ while (current != null ) {
16+ ListNode nextTemp = current .next ;
17+ current .next = prev ;
18+ prev = current ;
19+ current = nextTemp ;
20+ }
21+
22+ return prev ;
23+ }
24+
25+ public static void main (String [] args ) {
26+ // Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
27+ ListNode head = new ListNode (1 );
28+ head .next = new ListNode (2 );
29+ head .next .next = new ListNode (3 );
30+ head .next .next .next = new ListNode (4 );
31+ head .next .next .next .next = new ListNode (5 );
32+
33+ ReverseLinkedList solution = new ReverseLinkedList ();
34+ ListNode reversedHead = solution .reverseList (head );
35+
36+ // Print the reversed linked list: 5 -> 4 -> 3 -> 2 -> 1
37+ ListNode current = reversedHead ;
38+ while (current != null ) {
39+ System .out .print (current .val + " -> " );
40+ current = current .next ;
41+ }
42+ System .out .println ("null" );
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments