




Sponsored
Sponsored
This approach involves reversing the second half of the linked list and then comparing it with the first half. If they are identical, the linked list is a palindrome. The steps include:
Time Complexity: O(n) since we are traversing the list multiple times but each in linear time.
Space Complexity: O(1) as we are reversing the linked list in place.
1public class ListNode {
2    public int val;
3    public ListNode next;
4    public ListNode(int x) { val = x; }
5}
6
7public class Solution {
8    private ListNode ReverseList(ListNode head) {
9        ListNode prev = null;
10        ListNode current = head;
11        while (current != null) {
12            ListNode nextNode = current.next;
13            current.next = prev;
14            prev = current;
15            current = nextNode;
16        }
17        return prev;
18    }
19
20    public bool IsPalindrome(ListNode head) {
21        if (head == null || head.next == null) return true;
22        ListNode slow = head;
23        ListNode fast = head;
24        while (fast != null && fast.next != null) {
25            slow = slow.next;
26            fast = fast.next.next;
27        }
28        ListNode secondHalf = ReverseList(slow);
29        ListNode firstHalf = head;
30        while (secondHalf != null) {
31            if (firstHalf.val != secondHalf.val) return false;
32            firstHalf = firstHalf.next;
33            secondHalf = secondHalf.next;
34        }
35        return true;
36    }
37}The C# implementation mirrors the logic of reversing the second half of the list and checking against the first half similarly to the other languages.
In this approach, convert the linked list into an array and utilize a two-pointer technique to determine if it forms a palindrome. The steps are as follows:
Time Complexity: O(n) due to single traversation and subsequent O(n/2) check.
Space Complexity: O(n) because we store all node values in an array.
This C solution creates an array as large as the linked list to store values, which are then checked for palindromic order using two index pointers.