Advertisement
CreateWithChirag

Reverse Linked List

Jan 13th, 2023
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.70 KB | Source Code | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode() {}
  7.  *     ListNode(int val) { this.val = val; }
  8.  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9.  * }
  10.  */
  11. class Solution {
  12.     public ListNode reverseList(ListNode head) {
  13.         // Base case
  14.         if(head == null || head.next == null){
  15.             return head;
  16.         }
  17.  
  18.         ListNode prev = null;
  19.         ListNode curr = head;
  20.  
  21.         while(curr != null){
  22.             ListNode next = curr.next;
  23.             curr.next = prev;
  24.  
  25.             prev = curr;
  26.             curr = next;
  27.         }
  28.  
  29.         return prev;
  30.  
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement