두 목록이 정렬되면, 다음과 같은 알고리즘 (의사 코드, 실행의 복잡성 O(n+m)
)를 사용할 수 있습니다 : 목록 중 하나가 정렬되지 않은 경우
INPUT: list1, list2 (first nodes of the lists you want to compare, sorted!)
while list1 != null AND list2 != null
if list1->value < list2->value
list1->value = list1->next
elseif
list2->value < list1->value
list2->value = list2->next
else
list3->appendValue(list1->value)
list1->next
, 각 요소를 비교해야 두 번째 목록의 각 요소 (런타임 복잡성 O(n*m)
)와 첫 번째 목록에서 :
INPUT: list1, list2 (first nodes of the lists you want to compare)
while list1 != null
list2temp = list2
while list2temp != null
if list1->value == list2temp->value
list3->appendValue(list1->value)
list2temp = list2temp->next
list1 = list1->next
그것은 먼저 목록을 정렬 할 종종 더 나은 다음 첫 번째 방법을 사용,이 O(n log n + m log m)
의 런타임 복잡성이 발생합니다. 두 경우 모두 list3
에는 두 목록의 공통 요소가 포함됩니다.
가장 확실한 방법은 첫 번째 목록의 각 요소를 탐색하고 두 번째 목록의 각 요소와 비교하는 것입니다. – Aziz
@Aziz : 제발 주실 수 있습니까? – Nimit
http://www.c.happycodings.com/Data_Structures/code27.html –