iT邦幫忙

2024 iThome 鐵人賽

DAY 2
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 2

Day02__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

應該會暫時刷Linked List相關的LeetCode全部的easy題目,等到刷完再換其他類型,都刷完Easy之後,就該挑戰一下Medium~

234. Palindrome Linked List

tags: Easy、Linked-List

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

解法:

使用快慢指針來找中間點,當快指針到末端時,代表慢指針走到中間點,並將Linked List拆成兩半(上半部與下半部)進行比對

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool isPalindrome(struct ListNode* head) {
    struct ListNode *slow = head;
    struct ListNode *fast = head;
    if(head->next == NULL) {
        return true;
    }
    while (fast->next != NULL && fast->next->next != NULL) {
        slow = slow -> next;
        fast = fast -> next->next;
    }

    struct ListNode *current = slow -> next;
    struct ListNode *nextNode = NULL;
    struct ListNode *prev = NULL;
    slow->next = NULL;
    while (current != NULL) {
        nextNode = current->next;
        current->next = prev;
        prev = current;
        current = nextNode;
    }

    struct ListNode *compare = head;
    while (prev != NULL) {
        if (compare->val != prev->val) {
            return false;
        }
        compare = compare->next;
        prev = prev->next;
    }
    return true;

}

上一篇
Day01_C語言刷LeetCode
下一篇
Day03__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言