Untitled
unknown
plain_text
a year ago
1.1 kB
8
Indexable
public ListNode swapNodes(ListNode head, int k) {
// Step 1: Create a dummy node that points to the head
ListNode dummy = new ListNode(0);
dummy.next = head;
// Step 2: Find the kth node from the beginning (first) and its previous node
ListNode firstPrev = dummy, first = head;
for (int i = 1; i < k; i++) {
firstPrev = firstPrev.next;
first = first.next;
}
// Step 3: Find the kth node from the end (second) and its previous node
ListNode secondPrev = dummy, second = head;
ListNode temp = first;
while (temp.next != null) {
temp = temp.next;
secondPrev = secondPrev.next;
second = second.next;
}
// Step 4: Swap the nodes (not just the values)
// First, update the next pointers of the previous nodes
firstPrev.next = second;
secondPrev.next = first;
// Then, swap the next pointers of first and second
ListNode tempNext = first.next;
first.next = second.next;
second.next = tempNext;
// Step 5: Return the new head
return dummy.next;
}
Editor is loading...
Leave a Comment