엔지니어 블로그
[CodingTest] LinkedList 문제 본문
LinkedList 문제를 풀다가 코드를 개선하는 과정이 있어 글로 남깁니다.
문제
Q. 다음과 같은 두 링크드 리스트를 입력받았을 때, 합산한 값을 반환하시오.
예를 들어 아래와 같은 링크드 리스트를 입력받았다면,
각각 678, 354 이므로 두개의 총합
678 + 354 = 1032 를 반환해야 한다.
단, 각 노드의 데이터는 한자리 수 숫자만 들어갈 수 있다.
풀이
그냥 단순히 순회하면서 값을 list에 담고, 자리수에 맞춰서 수를 만들고 더한다는 아이디어로 시작했습니다. 그래서 코드가 이모양입니다... 너무 생각없이 한 것 같았습니다. 중복되는 것은 왜이리 많으며 그냥 의식의 흐름대로 했던 것 같습니다. 바로 반성하며 코드를 재구성해보기로 했습니다.
def get_sum_list():
list_1 = [];list_2 = []
current1 = linked_list_1.head
current2 = linked_list_2.head
while current1.next is not None:
list_1.append(str(current1.data))
list_2.append(str(current2.data))
current1 = current1.next
current2 = current2.next
list_1.append(str(current1.data))
list_2.append(str(current2.data))
return int("".join(list_1))+int("".join(list_2))
2차 풀이
1차 풀이보다는 조금 나아진 것처럼 보입니다. 주어지는 수의 각 자리수를 맞춰주는 것을 중점으로 생각하며 작성했습니다. 이것도 보니 중복되는 부분이 있어 한번 더 수정을 거치게 됩니다.
sum_1 = 0
cur_1 = linked_list_1.head
while cur_1 is not None:
sum_1 = sum_1 * 10 + cur_1.data
cur_1 = cur_1.next
sum_2 = 0
cur_2 = linked_list_2.head
while cur_2 is not None:
sum_2 = sum_2 * 10 + cur_2.data
cur_2 = cur_2.next
return sum_1 + sum_2
3차 풀이
이렇게 하니 코드 중복도 줄이고 가독성도 많이 올라간 것 같습니다. 앞으로는 절대 대충 짜지 않겠다고 다짐하며 이 글 마칩니다..
def get_sum_list(linked_list_1, linked_list_2):
return get_num(linked_list_1) + get_num(linked_list_2)
def get_num(linked_list):
sum = 0
cur = linked_list.head
while cur is not None:
sum = sum * 10 + cur.data
cur = cur.next
return sum
'알고리즘' 카테고리의 다른 글
[Leetcode] 763. Partition Labels (0) | 2025.04.01 |
---|---|
[Leetcode] 49. Group Anagrams (0) | 2025.02.27 |
[Leetcode] 20. Valid Parentheses (0) | 2025.02.20 |
[Leetcode] 392.Is Subsequence (0) | 2025.02.12 |
[LeetCode] 1. Two Sum (0) | 2025.02.01 |