Given a singly linked list, determine if it is a palindrome.
Example 1:
Input:1->2output:false
Example 2:
Input:1->2->2->1output:true
Follow up:
Could do it in O (n) time and O (1) space?
Please determine if a linked list is a palindrome list.
Example 1:
Input: 1->2 output: false
Example 2:
Input: 1->2->2->1 output: True
Advanced:
Can you solve this problem with O (n) time complexity and O (1) space complexity?
72ms
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * public var val:int5 * public var next:listnode?6 * Public init (_ Val:int) {7 * Self.val = val8 * Self.next = nil9 * }Ten * } One */ A classSolution { -Func Ispalindrome (_ Head:listnode?)Bool { - varRoot =Head the varstack =[ListNode] () - whileRoot! =Nil { -Stack.append (root!) -root = root?. Next + } - + varLow =0 A varHigh = Stack.count-1 at - whileLow <High { -Let Lownode =Stack[low] -Let Highnode =Stack[high] - - ifLownode.val = =Highnode.val { inLow + =1 -High-=1 to}Else { + return false - } the } * return true $ }Panax Notoginseng}
56ms
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * public var val:int5 * public var next:listnode?6 * Public init (_ Val:int) {7 * Self.val = val8 * Self.next = nil9 * }Ten * } One */ A classSolution { -Func Ispalindrome (_ Head:listnode?)Bool { - varslow =Head the varFast =Head - varReverse:listnode? =Nil - - whileFast?. Next! =Nil { +Fast = fast!. next!. Next -Let next = slow!. Next +slow!. Next =Reverse AReverse =Slow atslow =Next - } - ifFast! =Nil { -slow = slow!. Next - } - in whileSlow! =Nil { - ifslow!. Val! = reverse!. val { to return false + } -slow = slow!. Next theReverse = reverse!. Next * } $ Panax Notoginseng return true - } the}
60ms
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * public var val:int5 * public var next:listnode?6 * Public init (_ Val:int) {7 * Self.val = val8 * Self.next = nil9 * }Ten * } One */ A classSolution { -Func Ispalindrome (_ Head:listnode?)Bool { - varslow =Head the varFast =Head - varReverse: [INT] =[Int] () -Reverse.reservecapacity ( -) - + whileFast?. Next! =Nil { -Fast = fast!. next!. Next +Reverse.append (slow?. val)!) Aslow = slow?. Next at } - ifFast! =Nil { -slow = slow!. Next - } - - whileSlow! =Nil { in ifslow!. Val! =Reverse.poplast () { - return false to } +slow = slow!. Next - } the * return true $ }Panax Notoginseng}
234. Palindrome Chain List | Palindrome Linked List