题目:回文链表定义为链表正序和逆序输出结果一致,检验链表是否是回文链表.
解法一
可以将链表反转之后和现在的链表的顺序输出做对比.
<pre><code>` func isPalindrome(node:ListNode) -> Bool {
var headNode:ListNode? = node
var preNode:ListNode?
var reverseHeadNode:ListNode?
while headNode != nil {
let next:ListNode? = headNode?.next
if next == nil {
reverseHeadNode = headNode
}
headNode?.next = preNode
preNode = headNode
headNode = next
}
headNode = node
while headNode != nil {
if headNode?.value != reverseHeadNode?.value {
return false
}
headNode = headNode?.next
reverseHeadNode = reverseHeadNode?.next
}
return true
}`</code></pre>
解法二
可以先将链表遍历到链表中间,用数组将数据存储起来,然后继续遍历链表与数组最后的数字做对比.
<pre><code>` func isPalindrome1(node:ListNode) -> Bool {
var list:[String?] = []
var slow:ListNode? = node
var fast:ListNode? = node
while fast != nil && fast?.next != nil {
list.append(slow?.value)
slow = slow?.next
fast = fast?.next?.next
}
// 奇数个元素,跳过中间元素
if fast != nil {
slow = slow?.next
}
while slow != nil {
let data:String? = list.last!
list.removeLast()
if slow?.value != data {
return false
}
slow = slow?.next
}
return true
}`</code></pre>
测试代码:
<pre><code>`listNodeManger.headNode = nil
listNodeManger.appendToTail(value: "(1)")
listNodeManger.appendToTail(value: "(2)")
listNodeManger.appendToTail(value: "(3)")
listNodeManger.appendToTail(value: "(2)")
listNodeManger.appendToTail(value: "(1)")
var isRome:Bool = listNodeManger.isPalindrome(node: listNodeManger.headNode!)
if isRome {
print("FlyElephant---回文链表")
} else {
print("FlyElephant---非回文链表")
}
isRome = listNodeManger.isPalindrome1(node: listNodeManger.headNode!)
if isRome {
print("FlyElephant---回文链表")
} else {
print("FlyElephant---非回文链表")
}
`</code></pre>