-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathq234-palindrome-linked-list.swift
103 lines (86 loc) · 2.78 KB
/
q234-palindrome-linked-list.swift
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// q234-palindrome-linked-list.swift
// leetcode-swift
// Source* : https://leetcode.com/problems/palindrome-linked-list/
// Category* : LinkedList TwoPointers
//
// Created by Tianyu Wang on 16/7/7.
// Github : http://github.com/wty21cn
// Website : http://wty.im
// Linkedin : https://www.linkedin.com/in/wty21cn
// Mail : mailto:[email protected]
/**********************************************************************************
*
* Given a singly linked list, determine if it is a palindrome.
*
* Follow up:
* Could you do it in O(n) time and O(1) space?
*
**********************************************************************************/
import Foundation
struct q234 {
class Solution {
func findHalfOfLink(_ head: ListNode?) -> ListNode? {
var head = head
var fastPtr = head
while fastPtr?.next != nil {
head = head!.next
fastPtr = fastPtr!.next!.next
}
return head
}
func reverse(_ head: ListNode?) -> ListNode? {
var head = head
var p: ListNode? = nil
var n: ListNode? = head?.next
while head != nil {
head!.next = p
p = head
head = n
n = head?.next
}
return p
}
func isPalindrome(_ head: ListNode?) -> Bool{
var halfHead = reverse(findHalfOfLink(head))
var head = head
while head != nil && halfHead != nil {
guard head!.val == halfHead!.val else {
return false
}
head = head!.next
halfHead = halfHead!.next
}
return true
}
}
// This Solution will crash when the link is very long.
class Solution_StackOverFlow {
var ptr: ListNode?
func isPalindromeUtil(_ node: ListNode) -> Bool {
if let next = node.next {
guard isPalindromeUtil(next) else {
return false
}
}
guard ptr!.val == node.val else {
return false
}
ptr = ptr!.next
return true
}
func isPalindrome(_ head: ListNode?) -> Bool {
if let head = head {
ptr = head
return isPalindromeUtil(head)
} else {
return true
}
}
}
static func getSolution() -> Void {
let head = LinkedListHelper.buildLinkedList(withNodes: [1,1,2,1,1])
print(head ?? "")
print(Solution().isPalindrome(head))
}
}