Menu

Pattern: Reverse LinkedList
📰
0

Pattern: Reverse LinkedList

DEV Community·Prashant Mishra·about 1 month ago
#1XvmdeKO
Reading 0:00
15s threshold

Prashant Mishra

Reverse a LinkedList

/**
 * 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;
        while(head!=null){
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}

Enter fullscreen mode Exit fullscreen mode

Read More