Sheet 3
unknown
java
a year ago
2.8 kB
4
Indexable
public class PracticeSheet3 { static class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } } static class SwapNodes { public ListNode swapNodes(ListNode head, int position1, int position2) { if (head == null || position1 == position2) { return head; } ListNode prev1 = null, curr1 = head; ListNode prev2 = null, curr2 = head; // Traverse the list to find the nodes to swap for (int i = 1; curr1 != null && i < position1; i++) { prev1 = curr1; curr1 = curr1.next; } for (int i = 1; curr2 != null && i < position2; i++) { prev2 = curr2; curr2 = curr2.next; } // If one or both positions are out of bounds, return the original head if (curr1 == null || curr2 == null) { return head; } // If the nodes to swap are not adjacent if (prev1 != null && curr2.next != curr1) { prev1.next = curr2; } else if (prev1 == null) { // If the first position is the head head = curr2; } if (prev2 != null && curr1.next != curr2) { prev2.next = curr1; } else if (prev2 == null) { // If the second position is the head head = curr1; } // Swap the next pointers of the nodes to perform the swap ListNode temp = curr1.next; curr1.next = curr2.next; curr2.next = temp; return head; } // Helper method to print the linked list public void printList(ListNode head) { ListNode current = head; while (current != null) { System.out.print(current.val + " "); current = current.next; } System.out.println(); } } public static void main(String[] args) { SwapNodes swap = new SwapNodes(); // Example linked list: 1 -> 2 -> 3 -> 4 -> 5 ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); System.out.println("Original linked list:"); swap.printList(head); // Swap nodes at positions 2 and 4 head = swap.swapNodes(head, 2, 4); System.out.println("Linked list after swapping nodes:"); swap.printList(head); } } //output Original linked list: 1 2 3 4 5 Linked list after swapping nodes: 1 4 3 2 5
Editor is loading...
Leave a Comment