Given a linked list, swap every kth node in that. If at the end of the list remaining nodes are less than k, leave them untouched.
Input: A linked list, A number k.
classSolution {
public ListNode swapEveryKthNode(ListNode head, int k) {
// Edge case: If k <= 1 or the list is empty, no need to swapif (k <= 1 || head ==null) {
return head;
}
// Dummy node to handle the edge cases easily ListNode dummy =new ListNode(0);
dummy.next= head;
ListNode current = head;
ListNode prev = dummy;
while (true) {
ListNode start = current;
ListNode end = current;
ListNode prevEnd = current; // will be used to connect to the next part// Check if there are at least k nodes leftint count = 0;
while (count < k && current !=null) {
prevEnd = current;
current = current.next;
count++;
}
if (count < k) {
break; // If fewer than k nodes left, exit the loop }
// Perform the swap within this k-segment// Save prev pointers to 1st and last nodes in the segment ListNode firstNodePrev = prev;
ListNode firstNode = start;
ListNode kNodePrev = prevEnd;
ListNode kNode = prevEnd;
// Swap the first and k-th nodes firstNodePrev.next= kNode;
kNodePrev.next= firstNode;
ListNode temp = firstNode.next;
firstNode.next= kNode.next;
kNode.next= temp;
// Move prev pointer to the last node after the swap prev = firstNode;
}
return dummy.next;
}
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ListNode head = solution.createLinkedList(arr);
int k = 4; // swapping every 4th node System.out.println("Original list:");
solution.printLinkedList(head);
ListNode newHead = solution.swapEveryKthNode(head, k);
System.out.println("After swapping every 4th node:");
solution.printLinkedList(newHead);
}
}
defswapEveryKthNode(head: ListNode, k: int) -> ListNode:
# Edge case: If k <= 1 or the list is empty, no need to swapif k <=1or head isNone:
return head
# Dummy node to handle the edge cases easily dummy = ListNode(0)
dummy.next = head
current = head
prev = dummy
whileTrue:
start = current
end = current
prevEnd = current
# Check if there are at least k nodes left count =0while count < k and current isnotNone:
prevEnd = current
current = current.next
count +=1if count < k:
break# If fewer than k nodes left, exit the loop# Perform the swap within this k-segment# Save prev pointers to 1st and last nodes in the segment firstNodePrev = prev
firstNode = start
kNodePrev = prevEnd
kNode = prevEnd
# Swap the first and k-th nodes firstNodePrev.next = kNode
kNodePrev.next = firstNode
temp = firstNode.next
firstNode.next = kNode.next
kNode.next = temp
# Move prev pointer to the last node after the swap prev = firstNode
return dummy.next
# Example usage:arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
k =4head = create_linked_list(arr)
print("Original List:")
print_linked_list(head)
new_head = swapEveryKthNode(head, k)
print("After Swapping Every 4th Node:")
print_linked_list(new_head)