Skip to content
Related Articles
Open in App
Not now

Related Articles

Swap first odd and even valued nodes from the beginning and end of a Linked List

Improve Article
Save Article
  • Last Updated : 31 Jan, 2023
Improve Article
Save Article

Given a singly Linked List, the task is to swap the first odd valued node from the beginning and the first even valued node from the end of the Linked List. If the list contains node values of a single parity, then no modifications are required.

Examples:

Input: 4 -> 3 -> 5 -> 2 -> 3 -> NULL
Output: 4 -> 2 -> 5 -> 3 -> 3 -> NULL
Explanation: 4 -> 3 -> 5 -> 2 -> 3 -> NULL ===> 4 -> 2 -> 5 -> 3 -> 3 -> NULL The first odd value in any node from the beginning is 3. The first even value in any node from the end is 2. After swapping the above two node values, the linked list modifies to 4 -> 2 -> 5 -> 3 -> 3 -> NULL.

Input: LL: 2 -> 6 -> 8 -> 2 -> NULL
Output: 2 -> 6 -> 8 -> 2 -> NULL

Approach: The given problem can be solved by keeping track of the first and the last occurrences of odd and even valued nodes respectively and swapping them. Follow the steps below to solve the problem:

  • Initialize two variables, say firstOdd and firstEven, to store the first node having odd and even values from the beginning and the end respectively.
  • Initialize two variables, say firstOdd and firstEven (initially NULL).
  • Traverse the linked list and perform the following steps:
  • After completing the above steps, if firstOdd and firstEven is not NULL, then swap the values at both the pointers.
  • Print the modified Linked List as the resultant Linked List.

Below is the implementation of the above approach:

Python3




# Python3 program for the above approach
 
# Structure of a node
# in the Linked List
class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
# Function to display the Linked List
def printLL(head):
 
    # Traverse until end
    # of list is reached
    while(head):
     
        # Print the value
        # stored in the head
        print(head.val, end =' ')
         
        # Move to the next of head
        head = head.next
    print()
 
# Function to swap the nodes
def swapNodes(head, even, odd):
 
    # Keeps the track of
    # prevEven and CurrEven
    prevEven = None
    currEven = head
 
    while currEven and currEven != even:
        prevEven = currEven
        currEven = currEven.next
 
    # Keeps the track of
    # prevOdd and currOdd
    prevOdd = None
    currOdd = head
 
    while currOdd and currOdd != odd:
        prevOdd = currOdd
        currOdd = currOdd.next
 
    # If list contains nodes
    # of a single parity
    if not currEven or not currOdd:
        return head
 
    # If head of the linked list
    # does not contain even value
    if prevEven:
        prevEven.next = currOdd
 
    # Make odd node the new head
    else:
        head = currOdd
 
    # If head of the linked list
    # does not contain odd value
    if prevOdd:
        prevOdd.next = currEven
 
    # Make even node the new head
    else:
        head = currEven
 
    # Swap the next pointers
    temp = currEven.next
    currEven.next = currOdd.next
    currOdd.next = temp
 
    # Return the modified Linked List
    return head
 
# Function to swap the first odd node
# from the beginning and the first even
# node from the end of the Linked List
def swapOddAndEvenNodes(head):
 
    # Find the first even node from
    # the end of the Linked List
    even = None
    curr = head
    while curr:
        if not curr.val & 1:
            even = curr
        curr = curr.next
 
    # Find the first odd node from
    # the front of the Linked List
    odd = None
    curr = head
    while curr:
        if curr.val & 1:
            odd = curr
            break
        curr = curr.next
 
    # If required odd and even
    # nodes are found, then swap
    if odd and even:
        head = swapNodes(head, even, odd)
 
    printLL(head)
 
# Function to convert given
# array into a Linked List
def linkedList(arr):
    head = None
    ptr = None
 
    # 4 -> 3 -> 5 -> 2 -> 3 -> NULL
    for i in arr:
        if not head:
            head = Node(i)
            ptr = head
        else:
            newNode = Node(i)
            ptr.next = newNode
            ptr = newNode
    return head
 
# Driver Code
 
# Given Linked List
arr = [4, 3, 5, 2, 3]
 
# Stores head of Linked List
head = linkedList(arr)
 
swapOddAndEvenNodes(head)

Java




class Node {
    int val;
    Node next;
    Node(int x) { val = x; }
}
 
public class Main {
 
    // Function to display the Linked List
    public static void printLL(Node head)
    {
 
        // Traverse until end of list is reached
        while (head != null) {
            // Print the value stored in the head
            System.out.print(head.val + " ");
            // Move to the next of head
            head = head.next;
        }
        System.out.println();
    }
 
    // Function to swap the nodes
    public static Node swapNodes(Node head, Node even,
                                 Node odd)
    {
 
        // Keeps the track of prevEven and CurrEven
        Node prevEven = null;
        Node currEven = head;
 
        while (currEven != null && currEven != even) {
            prevEven = currEven;
            currEven = currEven.next;
        }
 
        // Keeps the track of prevOdd and currOdd
        Node prevOdd = null;
        Node currOdd = head;
 
        while (currOdd != null && currOdd != odd) {
            prevOdd = currOdd;
            currOdd = currOdd.next;
        }
 
        // If list contains nodes of a single parity
        if (currEven == null || currOdd == null) {
            return head;
        }
 
        // If head of the linked list does not contain even
        // value
        if (prevEven != null) {
            prevEven.next = currOdd;
        }
 
        // Make odd node the new head
        else {
            head = currOdd;
        }
 
        // If head of the linked list does not contain odd
        // value
        if (prevOdd != null) {
            prevOdd.next = currEven;
        }
 
        // Make even node the new head
        else {
            head = currEven;
        }
        // Swap the next pointers
        Node temp = currEven.next;
        currEven.next = currOdd.next;
        currOdd.next = temp;
 
        // Return the modified Linked List
        return head;
    }
 
    // Function to swap the first odd node
    // from the beginning and the first even
    // node from the end of the Linked List
    public static void swapOddAndEvenNodes(Node head)
    {
 
        // Find the first even node from
        // the end of the Linked List
        Node even = null;
        Node curr = head;
        while (curr != null) {
            if (curr.val % 2 == 0) {
                even = curr;
            }
            curr = curr.next;
        }
 
        // Find the first odd node from
        // the front of the Linked List
        Node odd = null;
        curr = head;
        while (curr != null) {
            if (curr.val % 2 != 0) {
                odd = curr;
                break;
            }
            curr = curr.next;
        }
 
        // If required odd and even
        // nodes are found, then swap
        if (odd != null && even != null) {
            head = swapNodes(head, even, odd);
        }
        printLL(head);
    }
 
    // Function to convert given array into a Linked List
    public static Node linkedList(int[] arr)
    {
        Node head = null;
        Node ptr = null;
 
        // 4 -> 3 -> 5 -> 2 -> 3 -> NULL
        for (int i : arr) {
            if (head == null) {
                head = new Node(i);
                ptr = head;
            }
            else {
                Node newNode = new Node(i);
                ptr.next = newNode;
                ptr = newNode;
            }
        }
        return head;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given Linked List
        int[] arr = { 4, 3, 5, 2, 3 };
 
        // Stores head of Linked List
        Node head = linkedList(arr);
 
        swapOddAndEvenNodes(head);
    }
}

Output:

4 2 5 3 3

Time Complexity: O(N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!