Skip to content

Latest commit

 

History

History
59 lines (43 loc) · 1.01 KB

234-palindrome-linked-list.md

File metadata and controls

59 lines (43 loc) · 1.01 KB

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

thinking

code

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func isPalindrome(head *ListNode) bool {
    var fast, slow, pre *ListNode = head, head, nil

	for fast != nil && fast.Next != nil {
		fast = fast.Next.Next

		next := slow.Next

		slow.Next = pre
		pre = slow
		slow = next
	}

	if fast != nil {
		slow = slow.Next
	}

	for slow != nil {
		if pre.Val != slow.Val {
			return false
		}
		slow = slow.Next
		pre = pre.Next
	}

	return true
}