Palindrome Linked List - Linked List - Easy - LeetCode
💻 coding

Palindrome Linked List - Linked List - Easy - LeetCode

1 min read 190 words
1 min read
ShareWhatsAppPost on X
  • 1The problem is to determine if a singly linked list is a palindrome.
  • 2The solution involves using a two-pointer technique to find the middle of the list.
  • 3The algorithm achieves O(n) time complexity and O(1) space complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem is to determine if a singly linked list is a palindrome."

Palindrome Linked List - Linked List - Easy - LeetCode

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2 Output: false Example 2:

Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * public int val;
 * public ListNode next;
 * public ListNode(int val=0, ListNode next=null) {
 * this.val = val;
 * this.next = next;
 * }
 * }
 */
public class Solution {
 public bool IsPalindrome(ListNode head) {
 ListNode fast = head;
 ListNode slow = head;
 while (fast != null && fast.next != null) {
 fast = fast.next.next;
 slow = slow.next;
 }
 
 if (fast != null) { // odd nodes: let right half smaller
 slow = slow.next;
 }
 
 slow = reverse(slow);
 fast = head;

 while (slow != null) {
 if (fast.val != slow.val) {
 return false;
 }
 fast = fast.next;
 slow = slow.next;
 }
 return true;
 }
 
 public ListNode reverse(ListNode head) {
 ListNode prev = null;
 while (head != null) {
 ListNode next = head.next;
 head.next = prev;
 prev = head;
 head = next;
 }
 return prev;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 30 September 2020 · 1 min read · 190 words

Part of AskGif Blog · coding

You might also like