在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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: 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶: 72ms 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func isPalindrome(_ head: ListNode?) -> Bool { 14 var root = head 15 var stack = [ListNode]() 16 while root != nil { 17 stack.append(root!) 18 root = root?.next 19 } 20 21 var low = 0 22 var high = stack.count - 1 23 24 while low < high { 25 let lownode = stack[low] 26 let highnode = stack[high] 27 28 if lownode.val == highnode.val { 29 low += 1 30 high -= 1 31 } else { 32 return false 33 } 34 } 35 return true 36 } 37 } 56ms 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func isPalindrome(_ head: ListNode?) -> Bool { 14 var slow = head 15 var fast = head 16 var reverse: ListNode? = nil 17 18 while fast?.next != nil { 19 fast = fast!.next!.next 20 let next = slow!.next 21 slow!.next = reverse 22 reverse = slow 23 slow = next 24 } 25 if fast != nil { 26 slow = slow!.next 27 } 28 29 while slow != nil { 30 if slow!.val != reverse!.val { 31 return false 32 } 33 slow = slow!.next 34 reverse = reverse!.next 35 } 36 37 return true 38 } 39 } 60ms 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func isPalindrome(_ head: ListNode?) -> Bool { 14 var slow = head 15 var fast = head 16 var reverse: [Int] = [Int]() 17 reverse.reserveCapacity(100) 18 19 while fast?.next != nil { 20 fast = fast!.next!.next 21 reverse.append((slow?.val)!) 22 slow = slow?.next 23 } 24 if fast != nil { 25 slow = slow!.next 26 } 27 28 while slow != nil { 29 if slow!.val != reverse.popLast() { 30 return false 31 } 32 slow = slow!.next 33 } 34 35 return true 36 } 37 }
|
请发表评论