
난이도: ★☆☆☆☆ • solved on: 2025-11-06


true, 다르면 false를 반환해야 한다.자료구조
SinglyLinkedListNode: 단일 연결 리스트의 노드 구조체data 값과 next 포인터를 가짐)알고리즘/기법
핵심 키워드
- 문제 분해
- 두 연결 리스트의 첫 노드부터 동시에 순회하면서
data를 비교한다.- 두 노드 중 하나라도 null에 먼저 도달하거나
data값이 다르면 false를 반환한다.
핵심 로직 흐름
while (head1 != null && head2 != null): if (head1.data != head2.data): return false head1 = head1.next head2 = head2.next // 반복문 종료 후, 둘 다 null이어야 true if (head1 != head2): return false else: return true예외 처리
- 두 리스트 중 하나만 null일 때 → 길이가 다르므로 false 반환
- 두 리스트가 모두 비어 있는 경우 → true 반환
static boolean compareLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
SinglyLinkedListNode headOneCurrent = head1;
SinglyLinkedListNode headTwoCurrent = head2;
while (headOneCurrent != null && headTwoCurrent != null) {
if (headOneCurrent.data != headTwoCurrent.data) {
return false;
}
headOneCurrent = headOneCurrent.next;
headTwoCurrent = headTwoCurrent.next;
}
if (headOneCurrent != headTwoCurrent) {
return false;
} else {
return true;
}
}
headOneCurrent != headTwoCurrent 검사 추가로 해결)head1 != head2 조건으로 길이 차이를 간단히 판별할 수 있다.비슷한 유형 (GPT 추천):
확장 문제 (GPT 추천):