Skip to content

Commit

Permalink
Create palindrome-linked-list.go
Browse files Browse the repository at this point in the history
  • Loading branch information
lluxury authored Feb 22, 2019
1 parent 88a2836 commit 9a69605
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions go/06_linkedlist/palindrome-linked-list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
var slow *ListNode = head
var fast *ListNode = head
var prev *ListNode = nil
var temp *ListNode = nil

if (head == nil || head.Next == nil) {
return true
}

for (fast != nil && fast.Next !=nil){
fast = fast.Next.Next
temp = slow.Next
slow.Next = prev
prev = slow
slow = temp
} // 快的先跑完,同时反转了一半链表,剪短

if fast != nil {
slow = slow.Next // 处理余数,跨过中位数
// prev 增加中 2->1->nil
}

var l1 *ListNode = prev
var l2 *ListNode = slow

for (l1 != nil && l2 !=nil && l1.Val == l2.Val){
l1 = l1.Next
l2 = l2.Next
}

return (l1 == nil && l2 == nil)

}

0 comments on commit 9a69605

Please sign in to comment.