GeeksforGeeks App
Open App
Browser
Continue

# Swap Kth node from beginning with Kth node from end in a 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:

## C#

Output

1 4 3 2 5

Time Complexity: O(K), As we are traversing till Kth element from tail and head of the list and then changing the links which is a O(1) operation.
Auxiliary Space: O(1), As constant extra space is used.

Method 2: Without swapping the elements and without using temporary node.

Approach: There are 3 cases in order to swap the nodes.

• Swapping the first and the last nodes (k = 1)
• Swapping the ordinary Kth node from the beginning and Kth node from the end.
• Swapping middle nodes

Case 1: Swap first and last nodes (k = 1)

Steps:

1. Make the list as a circular linked list
2. Change the previous pointer of the first node to the last but one node (20 in example figure)
3. Change the next pointer of last but one node to the last node. In this case it will be 60.
4. After swapping, make the head as the first node.
Consider p and q are the nodes which are to be swapped,

last = p; //change last pointer to point to last node

swapping first and last nodes

Case 2: Swapping the ordinary Kth node from the beginning and Kth node from the end.

Steps:

1. Let us consider K = 2. So the nodes to be swapped or interchanged are 20 and 50 as show in the figure.
2. Make both the first and next pointers of the nodes which are to be swapped to point to the previous nodes. To do this, we need to change the links of the previous nodes to point to the node which is after the node to be swapped.
Consider the nodes to be swapped are p and q:

//Change the link of the next pointer of the previous node to point to
//the next node of to be swapped node.
q.first.next = q.next;
p.first.next = p.next; // Same procedure for the other node

//Make sure to change the previous/first pointer of the next node to
//point to the previous of to be swapped node.
q.next.first = q.first;
p.next.first = p.first;

//Both the first and next pointers points to the previous node as shown in the below figure.
q.next = q.first;
p.next = p.first;

3. Interchange the pointers of one node to be swapped nodes with the other to be swapped node. (step 3 denotes the                 figure after interchanging).

4. Make the required changes in the links in order to make it as a complete list.

General case

Case 3: Swapping the middle nodes

Steps:

1. This case is same as the case 2 and the only change is, the nodes which are to be swapped are middle nodes. So both of them are together (side-by-side).
2. Consider p is the first node to be swapped and q is the second node to be swapped.
3. Point the next pointer of previous node of p to the next node of q. This step is done to omit p and q nodes.
4. In the same way, point the first pointer of next node of q to the previous node of q.
5. Change the links of p and q so that both the nodes points to the previous node of p (step2 in the below figure).
6. Make the links of p and q accordingly to make the nodes swap their positions.

To swap middle nodes

Implementation:

## Java

 // Java program to swap Kth node from beginning with// the Kth node from the end without using temporary// node and without swapping the datapublic class GFG{   // head pointer for pointing to start of the linked list  // last pointer for pointing to last node of the linked list  Node head = null,last = null;   // class Node  class Node{    int data;    Node first,next;    Node(int data){      this.data = data;      first = null;      next = null;    }  }   // function for inserting new node at the  // end of the list using last pointer  void AddLast(int data) {    Node temp = new Node(data);    if(head == null) {      head = temp;      last = temp;    }    else {      last.next = temp;      temp.first = last;      last = temp;    }  }   // function for printing the doubly linked list  void printList() {    Node p = head;    while(p!=null) {      System.out.print(p.data+"<->");      p = p.next;    }    System.out.print("null");    System.out.println();  }   // function for swapping Kth node from  // beginning with Kth node from the end  void swapKthNodes(int k) {    int count = 1;    Node p = head, q = last;     // case 1: to swap the start and end nodes    // case 1 figure    if(k == 1) {      q.first.next = p;      p.first = q.first;       q.next = p.next;      p.next.first = q;       // change these links to null to the break circular link      p.next = null;      q.first = null;       head = q;      last = p;    }    else {      while(p != null  &&  q != null  &&  count < k) {        count++;        p = p.next;        q = q.first;      }       // case 3: if the nodes to be swapped are the middle nodes      // given in the figure      if(p.next == q) {        p.first.next = p.next.next;        q.next.first = p.first;         p.next = p.first;        q.first = q.next = p.first;         q.next = p;        p.next.next.first = p;        p.next = p.first.next;         p.first.next = q;        p.first = q;      }      // case 2: other than middle nodes      // given in case 2 figure      else {        q.first.next = q.next;        q.next.first = q.first;        q.next = q.first;         p.first.next = p.next;        p.next.first = p.first;        p.next = p.first;         p.first = q.first;        q.first = p.next;         p.next = p.first;        q.next = q.first;         q.next = q.next.next;        q.first.next = q;        q.next.first = q;         p.next = p.next.next;        p.first.next = p;        p.next.first = p;      }    }  }   // Driver function  public static void main(String args[])  {     // class object    GFG list = new GFG();     // function calls for inserting    // at the end of the list    list.AddLast(10);    list.AddLast(20);    list.AddLast(30);    list.AddLast(40);    list.AddLast(50);    list.AddLast(60);     System.out.println("Before swapping:");    // print list before swapping the nodes    list.printList();    System.out.println();     // function call for swapping Kth nodes    list.swapKthNodes(1);     System.out.println("After swapping nodes for k = 1:");     // print list after swapping the nodes    list.printList();    System.out.println();     list.swapKthNodes(2);    System.out.println("After swapping nodes for k = 2:");    list.printList();    System.out.println();     list.swapKthNodes(3);    System.out.println("After swapping nodes for k = 3 (middle):");    list.printList();    System.out.println();  }} // This code is contributed by Likhita AVL

## Python3

 # Python program to swap Kth node from beginning with# the Kth node from the end without using temporary# node and without swapping the data # class Nodeclass Node:    def __init__(self, data):        self.data = data        self.first = None        self.next = None  class GFG:    # head pointer for pointing to start of the linked list    # last pointer for pointing to last node of the linked list    def __init__(self):        self.head = None        self.last = None     # function for inserting new node at the    # end of the list using last pointer    def AddLast(self, data):        temp = Node(data)        if self.head == None:            self.head = temp            self.last = temp        else:            self.last.next = temp            temp.first = self.last            self.last = temp     # function for printing the doubly linked list    def printList(self):        p = self.head        while p != None:            print(p.data, "<->", end="")            p = p.next        print("null")     # function for swapping Kth node from    # beginning with Kth node from the end    def swapKthNodes(self, k):        count = 1        p = self.head        q = self.last         # case 1: to swap the start and end nodes        # case 1 figure        if k == 1:            q.first.next = p            p.first = q.first             q.next = p.next            p.next.first = q             # change these links to null to the break circular link            p.next = None            q.first = None             self.head = q            self.last = p         else:            while p != None and q != None and count < k:                count += 1                p = p.next                q = q.first             # case 3: if the nodes to be swapped are the middle nodes            # given in the figure            if p.next == q:                p.first.next = p.next.next                q.next.first = p.first                 p.next = p.first                q.first = q.next = p.first                 q.next = p                p.next.next.first = p                p.next = p.first.next                 p.first.next = q                p.first = q             # case 2: other than middle nodes            # given in case 2 figure            else:                q.first.next = q.next                q.next.first = q.first                q.next = q.first                 p.first.next = p.next                p.next.first = p.first                p.next = p.first                 p.first = q.first                q.first = p.next                 p.next = p.first                q.next = q.first                 q.next = q.next.next                q.first.next = q                q.next.first = q                 p.next = p.next.next                p.first.next = p                p.next.first = p  # Driver functionif __name__ == '__main__':    # class object    list = GFG()     # function calls for inserting    # at the end of the list    list.AddLast(10)    list.AddLast(20)    list.AddLast(30)    list.AddLast(40)    list.AddLast(50)    list.AddLast(60)     print("Before swapping:")    # print list before swapping the nodes    list.printList()    print()     # function call for swapping Kth nodes    list.swapKthNodes(1)     print("After swapping nodes for k = 1:")    # print list after swapping the nodes    list.printList()    print()     list.swapKthNodes(2)    print("After swapping nodes for k = 2:")    list.printList()    print()     list.swapKthNodes(3)    print("After swapping nodes for k = 3 (middle):")    list.printList()    print() # This code is contributed by Tapesh(tapeshuda420)

## C#

 // C# program to swap Kth node from beginning with the Kth// node from the end without using temporary node and without// swapping the datausing System; public class GFG {     // class Node    class Node {        public int data;        public Node first, next;        public Node(int data)        {            this.data = data;            first = null;            next = null;        }    }     // head pointer for pointing to start of the linked list    // last pointer for pointing to last node of the linked    // list    Node head = null, last = null;     // function for inserting new node at the end of the    // list using last pointer    void AddLast(int data)    {        Node temp = new Node(data);        if (head == null) {            head = temp;            last = temp;        }        else {            last.next = temp;            temp.first = last;            last = temp;        }    }     // function for printing the doubly linked list    void printList()    {        Node p = head;        while (p != null) {            Console.Write(p.data + "<->");            p = p.next;        }        Console.Write("null");        Console.WriteLine();    }     // function for swapping Kth node from beginning with    // Kth node from the end    void swapKthNodes(int k)    {        int count = 1;        Node p = head, q = last;        // case 1: to swap the start and end nodes case 1        // figure        if (k == 1) {            q.first.next = p;            p.first = q.first;             q.next = p.next;            p.next.first = q;             // change these links to null to the break            // circular link            p.next = null;            q.first = null;             head = q;            last = p;        }        else {            while (p != null && q != null && count < k) {                count++;                p = p.next;                q = q.first;            }             // case 3: if the nodes to be swapped are the            // middle nodes given in the figure            if (p.next == q) {                p.first.next = p.next.next;                q.next.first = p.first;                 p.next = p.first;                q.first = q.next = p.first;                 q.next = p;                p.next.next.first = p;                p.next = p.first.next;                 p.first.next = q;                p.first = q;            }            // case 2: other than middle nodes given in case            // 2 figure            else {                q.first.next = q.next;                q.next.first = q.first;                q.next = q.first;                 p.first.next = p.next;                p.next.first = p.first;                p.next = p.first;                 p.first = q.first;                q.first = p.next;                 p.next = p.first;                q.next = q.first;                 q.next = q.next.next;                q.first.next = q;                q.next.first = q;                 p.next = p.next.next;                p.first.next = p;                p.next.first = p;            }        }    }     static public void Main()    {         GFG list = new GFG();         // function calls for inserting        // at the end of the list        list.AddLast(10);        list.AddLast(20);        list.AddLast(30);        list.AddLast(40);        list.AddLast(50);        list.AddLast(60);         Console.WriteLine("Before swapping:");        // print list before swapping the nodes        list.printList();        Console.WriteLine();         // function call for swapping Kth nodes        list.swapKthNodes(1);         Console.WriteLine(            "After swapping nodes for k = 1:");        // print list after swapping the nodes        list.printList();        Console.WriteLine();         list.swapKthNodes(2);        Console.WriteLine(            "After swapping nodes for k = 2:");        list.printList();        Console.WriteLine();         list.swapKthNodes(3);        Console.WriteLine(            "After swapping nodes for k = 3 (middle):");        list.printList();        Console.WriteLine();    }} // This code is contributed by lokesh (lokeshmvs21).

## Javascript

Output

Before swapping:
10<->20<->30<->40<->50<->60<->NULL

After swapping nodes for k = 1:
60<->20<->30<->40<->50<->10<->NULL

After swapping nodes for k = 2:
60<->50<->30<->40<->20<->10<->NULL

After swapping nodes for k = 3 (middle):
60<->50<->40<->30<->20<->10<->NULL

Time complexity: O(N) where N is number of nodes in linked list
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up