Q10 Reverse a LinkedList using add first | leetcode 206

PHOTO EMBED

Mon Jan 09 2023 11:50:16 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

/**
 * 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 {
    
//not making this static as static value will keep the values of previous test cases in them also therefore making it non static will reset the values back to null for next test case    
    public  ListNode th = null;
    public  ListNode tt = null;

    public void addfirst(ListNode node){
        if(th == null){
            th = node;
            tt = node;
        }
        else{
            node.next = th;
            th = node;
        }
    }
    public ListNode reverseList(ListNode head) {
        ListNode curr = head;

        while(curr!=null){
            ListNode temp = curr;
            curr = curr.next;
            temp.next = null;

            addfirst(temp);
        }
        return th;
    }
}








content_copyCOPY

https://leetcode.com/problems/reverse-linked-list/description/