Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 두 연결 목록의 목록 요소를 인터리브하는 프로그램

<시간/>

두 개의 연결 목록 l1과 l2가 있다고 가정하면 이 두 목록의 요소를 l1로 시작하여 인터리브하여 하나의 연결 목록을 반환해야 합니다. 연결 목록에 남은 노드가 있으면 목록에 추가해야 합니다.

따라서 입력이 l1 =[5,4,6,3,4,7] l2 =[8,6,9]와 같으면 출력은 [5,8,4,6,6,9, 3,4,7]

이 문제를 해결하기 위해 다음 단계를 따릅니다. −

  • 답변 :=l1

  • l2가 null이 아닌 동안 수행

    • ans가 null이 아니면

      • ans의 다음이 null이 아니면

        • newnode :=l2의 동일한 값을 가진 새 목록 노드

        • newnode의 다음 :=an의 다음

        • ans의 다음:=newnode

        • ans :=newnode의 다음

        • l2 :=l2의 다음

      • 그렇지 않으면

      • ans의 다음:=l2

      • 루프에서 나오다

    • 그렇지 않으면


      • 반환 l2


  • 리턴 l1

이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

예시

소스 코드(Python):class ListNode:def __init__(self, data, next =None):self.val =data self.next =nextdef make_list(elements):head =ListNode(elements[0]) for element in elements[1:]:ptr =head while ptr.next:ptr =ptr.next ptr.next =ListNode(element) return headdef print_list(head):ptr =head print('[', end ="") while ptr:print(ptr.val, end =", ") ptr =ptr.nextprint(']')class 솔루션:def solve(self, l1, l2):ans =l1 동안 l2:if ans:if ans.next !=없음:newnode =ListNode(l2.val, None) newnode.next =ans.next ans.next =newnode ans =newnode.next l2 =l2.next else:ans.next =l2 break else:return l2 return l1ob =솔루션()l1 =make_list([5,4,6,3,4,7])l2 =make_list([8,6,9])res =ob.solve(l1,l2)print_list(res) 

입력

[5,4,6,3,4,7],[8,6,9]

출력

[5, 8, 4, 6, 6, 9, 3, 4, 7, ]