iT邦幫忙

2024 iThome 鐵人賽

DAY 1
0
自我挑戰組

Leetcode 解題之旅:逐日攻克系列 第 1

每日一LeetCode(1)

  • 分享至 

  • xImage
  •  

234. Palindrome Linked List

題目敘述:

given the head of a singly linked list, return true if it is a palindromeor false otherwise.
Example 1:
https://ithelp.ithome.com.tw/upload/images/20240128/20162696vbJUhZBqbd.png
Input: head = [1,2,2,1]
Output: true
Example 2:
https://ithelp.ithome.com.tw/upload/images/20240128/20162696wAxhnjgwUR.png
Input: head = [1,2]
Output: false

程式碼(C++):

class Solution {
public:
    bool isPalindrome(ListNode* head) 
    {
        ListNode *slow = head, *fast = head, *prev, *temp;
        while(fast && fast->next)
            slow = slow->next, fast = fast->next->next;
            prev = slow, slow = slow->next, prev->next = NULL;
        while(slow)
            temp = slow->next, slow->next = prev,prev = slow, slow = temp;
            fast = head, slow = prev;
        while(slow)
            if(fast->val != slow->val) 
                return false;
            else 
                fast = fast ->next, slow = slow -> next;
        return true;
    }
};

下一篇
每日一LeetCode(2)
系列文
Leetcode 解題之旅:逐日攻克30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言