Home [Easy] Panlindrome Linked List
Post
Cancel

[Easy] Panlindrome Linked List

‘Panlindrome Linked List’ in LeetCode (Easy)


📌 Problem

https://leetcode.com/problems/palindrome-linked-list/

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * 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 boolean isPalindrome(ListNode head) {

        // 1. Copying the Linked List into an Array.
        List<Integer> vals = new ArrayList<>();
        ListNode currentNode = head;

        while (currentNode != null) {
            vals.add(currentNode.val);
            currentNode = currentNode.next;
        }

        // 2. Checking whether or not the Array is a palindrome.
        int front = 0;
        int back = vals.size() - 1;
        while (front < back) {
            if (!vals.get(front).equals(vals.get(back))) {
                return false;
            }
            front++;
            back--;
        }

        return true;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Data Sturcture] Tree Traversal (preorder, inorder, postorder)

[Data Sturcture] LinkedList (vs ArrayList)

Comments powered by Disqus.