코딩테스트/Leet Code
[Leet Code] 234. Palindrome Linked List
딥런
2022. 1. 14. 06:47
Palindrome Linked List
문제 설명
Given the head of a singly linked list, return true if it is a palindrome.
제한 사항
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9
입출력 예
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Python 코드
Python code
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
val_list = []
curr = head
while curr:
val_list.append(curr.val)
curr = curr.next
return val_list == val_list[::-1]
* 참고 링크 : https://ceuity.tistory.com/12
C++ 코드
C ++ code
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;
}
};
* 참고 링크 : https://dev.to/seanpgallivan/solution-palindrome-linked-list-5721
출처
https://leetcode.com/problems/palindrome-linked-list/submissions/