-
leetCode - Intersection of Two Linked Lists (LinkedList)프로그래밍/algorithm 2021. 7. 6. 09:46
문제
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
It is guaranteed that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
배경지식
연결리스트 - 원소들을 저장할 때, 그 다음 원소가 있는 위치를 포함시키는 방식으로 저장하는 자료구조.
- 특징
- k번째 원소를 확인/변경하기 위해 O(k(가 필요함
- 임의의 위치에 원소를 추가/임의 위치의 원소 제거는 O(1)
- 원소들이 메모리 상에 연속해 있지 않아 Cache hit rate가 낮지만 할당이 다소 쉬움
문제해결
*사진 출처: https://dev.to/seanpgallivan/solution-intersection-of-two-linked-lists-478e
1. 위 사진처럼 하나의 링크드 리스트가 끝날 때, 다른 링크드 리스트를 연결해준다.
2. 교점이 있다면 결국, 하나의 점에서 만나게 된다.
구현
const getIntersectionNode = function (headA, headB) { if (!headA && !headB) return null; let p1 = headA; let p2 = headB; while (p1 !== p2) { p1 = !p1 ? headA : p1.next; p2 = !p2 ? headB : p2.next; } return p1; };
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode - Reverse Linked List(LinkedList) (0) 2021.07.07 leetCode (Remove Linked List Elements)-LinkedList (0) 2021.07.06 leetCode (Two Sum II - Input array is sorted) - Array, Binary Search (0) 2021.07.01 leetCode (Pascal's Triangle) - Array, DP (0) 2021.06.28 leeCode (Maximum Subarray)-Array, Dp (0) 2021.06.26 - 특징