Untitled

 avatar
unknown
plain_text
13 days ago
1.2 kB
3
Indexable
public ListNode swapNodes(ListNode head, int k) {
    // Step 1: Find the kth node from the beginning
    ListNode firstPrev = null, first = head;
    for (int i = 1; i < k; i++) {
        firstPrev = first;
        first = first.next;
    }
    
    // Step 2: Find the kth node from the end using two pointers
    ListNode secondPrev = null, second = head;
    ListNode temp = first;
    while (temp.next != null) {
        temp = temp.next;
        secondPrev = second;
        second = second.next;
    }
    
    // Step 3: Swap the nodes
    // If firstPrev is not null, link firstPrev to second
    if (firstPrev != null) {
        firstPrev.next = second;
    } else {
        head = second; // If first is head, second becomes the new head
    }
    
    // If secondPrev is not null, link secondPrev to first
    if (secondPrev != null) {
        secondPrev.next = first;
    } else {
        head = first; // If second is head, first becomes the new head
    }
    
    // Swap the next pointers of first and second
    ListNode tempNext = first.next;
    first.next = second.next;
    second.next = tempNext;

    return head;
}
Leave a Comment