Leetcode - Remove Nth Node From End of List
Leetcode - Number of 1 Bits

Leetcode - Palindrome Linked List

violet posted @ Jun 25, 2020 05:58:38 AM in 算法 with tags Algorithm Golang Linked List , 335 阅读

https://leetcode.com/problems/palindrome-linked-list/

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

 

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func isPalindrome(head *ListNode) bool {
    fast := head
    slow := head
    count := 0
    for fast != nil {
        fast = fast.Next
        count++
        if fast == nil {
            break
        }
        count++
        fast = fast.Next
        slow = slow.Next
    }
    node := head
    var prev *ListNode
    for node != slow {
        tmp := node.Next
        node.Next = prev
        prev = node
        node = tmp
    }
    node1 := prev
    node2 := slow
    if count % 2 == 1 {
        node2 = node2.Next
    }
    
    for node1 != nil && node2 != nil {
        if node1.Val != node2.Val {
            return false
        }
        node1 = node1.Next
        node2 = node2.Next
    }
    if node1 != nil || node2 != nil {
        return false
    }
    return true
}
+1 Model Paper 2024 说:
Feb 11, 2023 04:41:27 PM

This will help students study more effectively and manage their time more effectively. The exams started in March. Please Read the Entire Article Below to Learn More About Model Paper 2024. +1 Model Paper 2024 For each topic, all examinees can receive the Board 11th Model Question Paper 2024 and the Board Inter Previous Question Paper 2024. To help all applicants who are taking the exam.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter