File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
Leetcode/leetcodeTags/LinkedList Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ package LinkedList ;
2+
3+ public class ReverseLinkedList206 {
4+
5+ public class ListNode {
6+ int val ;
7+ ListNode next ;
8+
9+ ListNode () {
10+ }
11+
12+ ListNode (int val ) {
13+ this .val = val ;
14+ }
15+
16+ ListNode (int val , ListNode next ) {
17+ this .val = val ;
18+ this .next = next ;
19+ }
20+ }
21+
22+ // using recursion
23+ public ListNode reverseList (ListNode head ) {
24+ return recursiveReverse (head );
25+ }
26+
27+ private ListNode recursiveReverse (ListNode head ) {
28+
29+ if (head == null || head .next == null )
30+ return head ;
31+
32+ ListNode newHead = recursiveReverse (head .next );
33+
34+ head .next .next = head ;
35+ head .next = null ;
36+
37+ return newHead ;
38+ }
39+
40+ // using iterative approach
41+ public ListNode reverseListIterative (ListNode head ) {
42+
43+ if (head == null || head .next == null )
44+ return head ;
45+
46+ ListNode prev = head ;
47+ ListNode curr = head .next ;
48+ ListNode nextNode = head .next .next ;
49+ prev .next = null ; // head node pointing to null as it will be tail at the end
50+
51+ while (curr .next != null ) {
52+ curr .next = prev ;
53+ prev = curr ;
54+ curr = nextNode ;
55+ nextNode = curr .next ;
56+ }
57+
58+ // pointing last node to second last node
59+ curr .next = prev ;
60+
61+ return curr ;
62+ }
63+
64+ }
You can’t perform that action at this time.
0 commit comments