Apex DSA - Reverse a Linked List - Salesforce
Reverse a Linked List
Problem Statement:
Given a linked list, reverse it and return the new head.
Example:
plaintext
CopyEdit
Input: 5 -> 4 -> 3 -> 2 -> 1
Output: 1 -> 2 -> 3 -> 4 -> 5
Solution :
// Define ListNode as a top-level class
public class ListNode {
public Integer val;
public ListNode next;
public ListNode(Integer val) {
this.val = val;
this.next = null;
}
}
//Build logic for reverse LinkedList
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
//Test LinkedList Logic
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// Print the original linked list
system.debug('originalLinkedList : '+head);
// Reverse the linked list
ReverseLinkedList op=new ReverseLinkedList();
ListNode reversedHead = op.reverseList(head);
// Print the reversed linked list
system.debug('reversedLinkedList : '+reversedHead);
Comments
Post a Comment