Skip to content

feat: add swift implementation to lcof2 problem: No.027 #3026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions lcof2/剑指 Offer II 027. 回文链表/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,55 @@ public class Solution {
}
```

#### Swift

```swift
/**
* Definition for singly-linked list.
* public class ListNode {
* var val: Int
* var next: ListNode?
* init() { self.val = 0; self.next = nil; }
* init(_ val: Int) { self.val = val; self.next = nil; }
* init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/

class Solution {
func isPalindrome(_ head: ListNode?) -> Bool {
guard let head = head else { return true }

var slow = head
var fast = head.next
while fast != nil && fast?.next != nil {
slow = slow.next!
fast = fast?.next?.next
}

var cur = slow.next
slow.next = nil
var prev: ListNode? = nil
while cur != nil {
let nextTemp = cur?.next
cur?.next = prev
prev = cur
cur = nextTemp
}

var left = head
var right = prev
while right != nil {
if left.val != right?.val {
return false
}
left = left.next!
right = right?.next
}
return true
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
44 changes: 44 additions & 0 deletions lcof2/剑指 Offer II 027. 回文链表/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* var val: Int
* var next: ListNode?
* init() { self.val = 0; self.next = nil; }
* init(_ val: Int) { self.val = val; self.next = nil; }
* init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/

class Solution {
func isPalindrome(_ head: ListNode?) -> Bool {
guard let head = head else { return true }

var slow = head
var fast = head.next
while fast != nil && fast?.next != nil {
slow = slow.next!
fast = fast?.next?.next
}

var cur = slow.next
slow.next = nil
var prev: ListNode? = nil
while cur != nil {
let nextTemp = cur?.next
cur?.next = prev
prev = cur
cur = nextTemp
}

var left = head
var right = prev
while right != nil {
if left.val != right?.val {
return false
}
left = left.next!
right = right?.next
}
return true
}
}
Loading