일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 파이썬기초100제
- Stack
- codeup
- 릿코드
- nlp
- 생성형AI
- 코드업
- gcp
- Python3
- two-pointer
- heap
- 파이썬
- 리트코드
- dfs
- 슬라이딩윈도우
- GenAI
- Python
- 파이썬알고리즘
- sql코테
- stratascratch
- slidingwindow
- GenerativeAI
- Greedy
- SQL
- LeetCode
- 알고리즘
- 니트코드
- 자연어처리
- array
- 투포인터
Archives
- Today
- Total
Tech for good
[Leetcode/Stack] 234. Palindrome Linked List 본문
💡 Key Idea (using stack):
Use a stack (LIFO) to store the values of the nodes. Then, go through the list again and compare each node’s value with the value popped from the stack. If all match, it's a palindrome.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
# Step 1: Traverse the list and push all values onto a stack
stack = []
current = head
while current:
stack.append(current.val)
current = current.next
# Step 2: Traverse the list again and compare with stack (LIFO order)
current = head
while current:
if current.val != stack.pop():
return False
current = current.next
return True
🧠 Step-by-Step Explanation:
Let’s use an example:
Input linked list: 1 → 2 → 2 → 1
Step 1: Traverse the list and push values onto a stack
We initialize an empty list stack = [].
We iterate through the linked list:
- Visit node with value 1: stack = [1]
- Visit node with value 2: stack = [1, 2]
- Visit node with value 2: stack = [1, 2, 2]
- Visit node with value 1: stack = [1, 2, 2, 1]
Now the stack contains all values in order of appearance.
Step 2: Traverse the list again and compare values
We start again from the head of the list and pop values from the stack:
- Current node: 1, popped from stack: 1 → ✅ match
- Current node: 2, popped from stack: 2 → ✅ match
- Current node: 2, popped from stack: 2 → ✅ match
- Current node: 1, popped from stack: 1 → ✅ match
If any values didn’t match, we would return False. Since all values match, we return True.
⏱️ Time & Space Complexity:
- Time: O(n) — we traverse the list twice
- Space: O(n) — we store all node values in the stack
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/Stack,Tree] 897. Increasing Order Search Tree (0) | 2025.04.16 |
---|---|
[Leetcode/Stack] 682. Baseball Game (0) | 2025.04.16 |
[Leetcode/Stack] 496. Next Greater Element I (0) | 2025.04.14 |
[Leetcode/Heap] 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (0) | 2025.04.11 |
[Neetcode/Heap] Last Stone Weight (0) | 2025.04.11 |