연결 리스트 노드 조작: 쌍 교체, 순위 기반 삭제, 교차점 탐지, 순환 감지

노드 쌍 교체

인접 노드 교체를 위해 가상 헤드 노드를 생성합니다. 현재 포인터를 가상 헤드에 위치시킨 후, 다음 두 노드가 존재할 때까지 반복합니다. 세 개의 임시 포인터를 활용해 노드 연결 관계를 재구성합니다.

class ListNode:
    def __init__(self, value=0, next_node=None):
        self.val = value
        self.next = next_node

def swap_node_pairs(head):
    dummy_head = ListNode(next_node=head)
    current = dummy_head
    while current.next and current.next.next:
        first = current.next
        second = current.next.next
        third = current.next.next.next
        
        current.next = second
        second.next = first
        first.next = third
        current = first
    return dummy_head.next

연결 리스트의 끝에서 N번째 노드 제거

전체 노드 개수를 계산한 후, 제거 대상의 선행 노드까지 이동합니다. 포인터 조정을 통해 타겟 노드를 건너뛰고 연결을 재설정합니다.

def remove_from_end(head, n):
    counter = 0
    temp_head = ListNode(next_node=head)
    pointer = temp_head
    
    while pointer.next:
        pointer = pointer.next
        counter += 1
        
    pointer = temp_head
    for _ in range(counter - n):
        pointer = pointer.next
        
    pointer.next = pointer.next.next
    return temp_head.next

연결 리스트 교차점 탐지

두 포인터를 각 리스트의 헤드에 배치합니다. 포인터가 리스트 끝에 도달하면 상대방 리스트의 헤드로 이동시킵니다. 교차점에서 두 포인터가 만나거나 동시에 None이 될 때까지 진행합니다.

def find_intersection(list_a, list_b):
    ptr1, ptr2 = list_a, list_b
    while ptr1 != ptr2:
        ptr1 = ptr1.next if ptr1 else list_b
        ptr2 = ptr2.next if ptr2 else list_a
    return ptr1

순환 연결 리스트 감지 및 시작점 탐색

느린 포인터와 빠른 포인터를 이용해 순환 존재 여부를 확인합니다. 순환 감지 후 한 포인터를 헤드로 재설정하고 동일 속도로 이동시켜 순환 시작점을 찾습니다.

def detect_cycle_start(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            break
    else:
        return None
    
    fast = head
    while fast != slow:
        fast, slow = fast.next, slow.next
    return fast

태그: 연결리스트 노드조작 포인터연산 파이썬알고리즘 자료구조

7월 2일 04:37에 게시됨