leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

palindrome-linked-list.dart (1097B)


      1 //Find if the values contained within a linked list are a palindrome.
      2 //To do this I iterated through the list putting all of the values into
      3 //an array and then at the end I checked to make sure the second half of the 
      4 //array was the same as the first half.
      5 //The time complexity of this is O(n) where n is the number of nodes in the list.
      6 
      7 //Runtime: 339ms Beats: 68.25%
      8 //Memory: 208.8MB Beats: 17.46%
      9 
     10 
     11 /**
     12  * Definition for singly-linked list.
     13  * class ListNode {
     14  *   int val;
     15  *   ListNode? next;
     16  *   ListNode([this.val = 0, this.next]);
     17  * }
     18  */
     19 class Solution {
     20   bool isPalindrome(ListNode? head) {
     21       if(head?.next == null){
     22           return true;
     23       }
     24 
     25       List<int> nums = [];
     26       while(true){
     27           if(head == null){
     28               break;
     29           }
     30           nums.add(head?.val ?? 0);
     31           head = head?.next;
     32       }
     33       
     34       for(int i = 0 ; i < (nums.length / 2).ceil() ; ++i){
     35           if(nums[i] == nums[nums.length - 1 - i]){
     36               continue;
     37           }
     38           else{
     39               return false;
     40           }
     41       }
     42 
     43       return true;
     44   }
     45 }