Swap Kth node from beginning with Kth node from end in a Doubly Linked List

Prerequisites: Doubly Linked List
Given a doubly-linked list, the task is to swap Kth node from the beginning with Kth node from the ending.

Note: Please note here the nodes are swapped and not the data in the nodes.

Examples:

Input: DLL = 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6, K = 3
Output: 1 2 4 3 5 6
Explanation:
Third node from the beginning(3) is swapped with third node from the ending(4).

Input: DLL = 1 <-> 2 <-> 3 <-> 4 <-> 5, K = 1
Output: 5 2 3 4 1



Approach: The idea is to traverse to the Kth element from the beginning and Kth node from the ending and change the previous and next pointers. Let K1 be the Kth node from beginning and K2 be Kth node from ending. Then:

  • The previous node to K2 has to be changed to the previous node of K1.
  • The next node to K2 has to be changed to the next node of K1.
  • The previous node to K1 has to be changed to the previous node of K2.
  • The next node to K1 has to be changed to the next node of K2.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
  
public class GFG {
  
    // Doubly Linked List implementation
    private class Node {
        private int data;
        private Node next;
        private Node previous;
  
        public Node(int data, Node next,
                    Node previous)
        {
            this.data = data;
            this.next = next;
            this.previous = previous;
        }
  
        public int getData()
        {
            return data;
        }
  
        public void setData(int data)
        {
            this.data = data;
        }
  
        public Node getNext()
        {
            return next;
        }
  
        public void setNext(Node next)
        {
            this.next = next;
        }
  
        public Node getPrevious()
        {
            return previous;
        }
  
        public void setPrevious(Node previous)
        {
            this.previous = previous;
        }
    }
  
    private Node head;
    private Node tail;
  
    public GFG()
    {
        this.head = null;
        this.tail = null;
    }
  
    public Node getHead()
    {
        return head;
    }
  
    public void setHead(Node head)
    {
        this.head = head;
    }
  
    public Node getTail()
    {
        return tail;
    }
  
    public void setTail(Node tail)
    {
        this.tail = tail;
    }
  
    // Function to replace Kth node from
    // beginning with Kth node from end
    public void swapNode(Node headReference,
                         Node tailReference, int k)
    {
  
        // If K is 1, then the first node
        // has to be swapped with the
        // last node in the doubly linked list
        if (k == 1) {
            swapFirstAndLast(headReference,
                             tailReference);
            return;
        }
  
        // If k is N, then the last node
        // has to be swapped with the
        // first node in the doubly linked list
        int nodeCount = getCount(headReference);
        if (k == nodeCount) {
            swapFirstAndLast(headReference,
                             tailReference);
            return;
        }
  
        // If the K<sup>th</sup> node from
        // the beginning and K<sup>th</sup> node
        // from the ending are same
        if (2 * k - 1 == nodeCount) {
            return;
        }
  
        // fNode represents K<sup>th</sup> node
        // from the beginning
        Node fNode = headReference;
        for (int i = 1; i < k; i++) {
            fNode = fNode.getNext();
        }
        Node fNodePrevious = fNode.getPrevious();
        Node fNodeNext = fNode.getNext();
  
        // sNode represents K<sup>th</sup> node
        // from the ending
        Node sNode = tailReference;
        for (int i = 1; i < k; i++) {
            sNode = sNode.getPrevious();
        }
  
        Node sNodePrevious = sNode.getPrevious();
        Node sNodeNext = sNode.getNext();
  
        // Checking if any of the pointers is null
        // and interchanging the pointers
        if (fNodePrevious != null && sNode != null) {
  
            fNodePrevious.setNext(sNode);
            sNode.setPrevious(fNodePrevious);
            sNode.setNext(fNodeNext);
            fNodeNext.setPrevious(sNode);
        }
        if (sNodePrevious != null && sNodeNext != null) {
  
            sNodeNext.setPrevious(fNode);
            fNode.setNext(sNodeNext);
            sNodePrevious.setNext(fNode);
            fNode.setPrevious(sNodePrevious);
        }
    }
  
    // Function to swap the first and
    // last node in the doubly linked list
    private void swapFirstAndLast(
        Node headReference,
        Node tailReference)
    {
        Node headRef = headReference;
        Node tailRef = tailReference;
  
        headReference
            = headReference.getNext();
        tailReference
            = tailReference.getPrevious();
  
        tailReference.setNext(headRef);
        headRef.setPrevious(tailReference);
        headRef.setNext(null);
        this.setTail(tailReference.getNext());
  
        headReference.setPrevious(tailRef);
        tailRef.setNext(headReference);
        tailRef.setPrevious(null);
        this.setHead(headReference
                         .getPrevious());
    }
  
    // Function to return the number of nodes
    // in the linked list
    private int getCount(Node headReference)
    {
        int nodeCount = 0;
        while (headReference != null) {
            nodeCount++;
            headReference = headReference
                                .getNext();
        }
        return nodeCount;
    }
  
    // Function to print the Linked List
    public void printList(Node headReference)
    {
        if (headReference == null) {
            System.out.println(
                "Doubly linked list is empty");
            return;
        }
        else {
            while (headReference != null) {
                System.out.print(
                    headReference.getData()
                    + " ");
                headReference
                    = headReference.getNext();
            }
        }
    }
  
    // Function to insert a node at
    // the end of the doubly linked list
    public void push(int data)
    {
        Node newNode
            = new Node(data, null, null);
  
        if (head == null) {
            head = tail = newNode;
        }
        else {
            tail.setNext(newNode);
            newNode.setPrevious(tail);
            tail = newNode;
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating an object for the class
        GFG list = new GFG();
  
        // Adding data to the linked list
        list.push(1);
        list.push(2);
        list.push(3);
        list.push(4);
        list.push(5);
  
        // Calling the function
        int K = 2;
        list.swapNode(list.getHead(),
                      list.getTail(), K);
        list.printList(list.getHead());
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
public class GFG {
   
    // Doubly Linked List implementation
    private class Node {
        private int data;
        private Node next;
        private Node previous;
   
        public Node(int data, Node next,
                    Node previous)
        {
            this.data = data;
            this.next = next;
            this.previous = previous;
        }
   
        public int getData()
        {
            return data;
        }
   
        public void setData(int data)
        {
            this.data = data;
        }
   
        public Node getNext()
        {
            return next;
        }
   
        public void setNext(Node next)
        {
            this.next = next;
        }
   
        public Node getPrevious()
        {
            return previous;
        }
   
        public void setPrevious(Node previous)
        {
            this.previous = previous;
        }
    }
   
    private Node head;
    private Node tail;
   
    public GFG()
    {
        this.head = null;
        this.tail = null;
    }
   
    Node getHead()
    {
        return head;
    }
   
    void setHead(Node head)
    {
        this.head = head;
    }
   
    Node getTail()
    {
        return tail;
    }
   
    void setTail(Node tail)
    {
        this.tail = tail;
    }
   
    // Function to replace Kth node from
    // beginning with Kth node from end
    void swapNode(Node headReference,
                         Node tailReference, int k)
    {
   
        // If K is 1, then the first node
        // has to be swapped with the
        // last node in the doubly linked list
        if (k == 1) {
            swapFirstAndLast(headReference,
                             tailReference);
            return;
        }
   
        // If k is N, then the last node
        // has to be swapped with the
        // first node in the doubly linked list
        int nodeCount = getCount(headReference);
        if (k == nodeCount) {
            swapFirstAndLast(headReference,
                             tailReference);
            return;
        }
   
        // If the K<sup>th</sup> node from
        // the beginning and K<sup>th</sup> node
        // from the ending are same
        if (2 * k - 1 == nodeCount) {
            return;
        }
   
        // fNode represents K<sup>th</sup> node
        // from the beginning
        Node fNode = headReference;
        for (int i = 1; i < k; i++) {
            fNode = fNode.getNext();
        }
        Node fNodePrevious = fNode.getPrevious();
        Node fNodeNext = fNode.getNext();
   
        // sNode represents K<sup>th</sup> node
        // from the ending
        Node sNode = tailReference;
        for (int i = 1; i < k; i++) {
            sNode = sNode.getPrevious();
        }
   
        Node sNodePrevious = sNode.getPrevious();
        Node sNodeNext = sNode.getNext();
   
        // Checking if any of the pointers is null
        // and interchanging the pointers
        if (fNodePrevious != null && sNode != null) {
   
            fNodePrevious.setNext(sNode);
            sNode.setPrevious(fNodePrevious);
            sNode.setNext(fNodeNext);
            fNodeNext.setPrevious(sNode);
        }
        if (sNodePrevious != null && sNodeNext != null) {
   
            sNodeNext.setPrevious(fNode);
            fNode.setNext(sNodeNext);
            sNodePrevious.setNext(fNode);
            fNode.setPrevious(sNodePrevious);
        }
    }
   
    // Function to swap the first and
    // last node in the doubly linked list
    private void swapFirstAndLast(
        Node headReference,
        Node tailReference)
    {
        Node headRef = headReference;
        Node tailRef = tailReference;
   
        headReference
            = headReference.getNext();
        tailReference
            = tailReference.getPrevious();
   
        tailReference.setNext(headRef);
        headRef.setPrevious(tailReference);
        headRef.setNext(null);
        this.setTail(tailReference.getNext());
   
        headReference.setPrevious(tailRef);
        tailRef.setNext(headReference);
        tailRef.setPrevious(null);
        this.setHead(headReference
                         .getPrevious());
    }
   
    // Function to return the number of nodes
    // in the linked list
    private int getCount(Node headReference)
    {
        int nodeCount = 0;
        while (headReference != null) {
            nodeCount++;
            headReference = headReference
                                .getNext();
        }
        return nodeCount;
    }
   
    // Function to print the Linked List
    void printList(Node headReference)
    {
        if (headReference == null) {
            Console.WriteLine(
                "Doubly linked list is empty");
            return;
        }
        else {
            while (headReference != null) {
                Console.Write(
                    headReference.getData()
                    + " ");
                headReference
                    = headReference.getNext();
            }
        }
    }
   
    // Function to insert a node at
    // the end of the doubly linked list
    void Push(int data)
    {
        Node newNode
            = new Node(data, null, null);
   
        if (head == null) {
            head = tail = newNode;
        }
        else {
            tail.setNext(newNode);
            newNode.setPrevious(tail);
            tail = newNode;
        }
    }
   
    // Driver code
    public static void Main(String[] args)
    {
   
        // Creating an object for the class
        GFG list = new GFG();
   
        // Adding data to the linked list
        list.Push(1);
        list.Push(2);
        list.Push(3);
        list.Push(4);
        list.Push(5);      
              
        // Calling the function
        int K = 2;
        list.swapNode(list.getHead(),
                      list.getTail(), K);
        list.printList(list.getHead());
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

1 4 3 2 5

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : 29AjayKumar

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.