Swap Kth node from beginning with Kth node from end in a Doubly Linked List
Last Updated :
12 Jul, 2025
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:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Node structure of the doubly linked list
struct Node {
int data;
Node* next;
Node* previous;
};
// Class of the doubly linked list
class GFG {
// head of the doubly linked list
Node* head;
// tail of the doubly linked list
Node* tail;
public:
// Default constructor
GFG()
{
head = tail = NULL;
}
// Function to return the head of the
// doubly linked list
Node* getHead()
{
return head;
}
// Function to set the head of the
// doubly linked list
void setHead(Node* head)
{
this->head = head;
}
// Function to return the tail of the
// doubly linked list
Node* getTail()
{
return tail;
}
// Function to set the tail of the
// doubly linked list
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->next;
}
Node* fNodePrevious = fNode->previous;
Node* fNodeNext = fNode->next;
// sNode represents K<sup>th</sup> node
// from the ending
Node* sNode = tailReference;
for (int i = 1; i < k; i++) {
sNode = sNode->previous;
}
Node* sNodePrevious = sNode->previous;
Node* sNodeNext = sNode->next;
// Checking if any of the pointers is null
// and interchanging the pointers
if (fNodePrevious != NULL && sNode != NULL) {
fNodePrevious->next = sNode;
sNode->previous
= fNodePrevious;
sNode->next = fNodeNext;
fNodeNext->previous
= sNode;
}
if (sNodePrevious != NULL
&& sNodeNext != NULL) {
sNodeNext->previous
= fNode;
fNode->next
= sNodeNext;
sNodePrevious
->next = fNode;
fNode->previous
= sNodePrevious;
}
}
// Function to swap the first and
// last node in the doubly linked list
void swapFirstAndLast(Node* headReference,
Node* tailReference)
{
Node* headRef = headReference;
Node* tailRef = tailReference;
headReference
= headReference->next;
tailReference
= tailReference->previous;
tailReference->next
= headRef;
headRef->previous
= tailReference;
headRef->next = NULL;
this->setTail(tailReference
->next);
headReference->previous
= tailRef;
tailRef->next
= headReference;
tailRef->previous
= NULL;
this->setHead(headReference
->previous);
}
// Function to return the number of nodes
// in the linked list
int getCount(Node* headReference)
{
int nodeCount = 0;
while (headReference != NULL) {
nodeCount++;
headReference
= headReference->next;
}
return nodeCount;
}
// Function to print the Linked List
void printList(Node* headReference)
{
if (headReference == NULL) {
cout << "Doubly linked list is empty";
return;
}
else {
while (headReference
!= NULL) {
cout << headReference->data
<< " ";
headReference
= headReference->next;
}
}
}
// Function to insert a node at
// the end of the doubly linked list
void push(int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
newNode->previous = NULL;
if (head == NULL) {
head = tail = newNode;
}
else {
tail->next = newNode;
newNode->previous = tail;
tail = newNode;
}
}
};
// Driver code
int main()
{
// Creating an object for the class
GFG list;
// 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());
return 0;
}
Java
// 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());
}
}
Python3
# Python implementation of the approach
# Node structure of the doubly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getNext(self, ):
return next
def setNext(self, next):
self.next = next
def getPrevious(self):
return previous
def setPrevious(self, previous):
self.previous = previous
# Class of the doubly linked list
class GFG:
# head of the doubly linked list
def __init__(self):
self.head = None
# tail of the doubly linked list
self.tail = None
# Function to return the head of the doubly linked list
def getHead(self):
return self.head
# Function to set the head of the doubly linked list
def setHead(self, head):
self.head = head
# Function to return the tail of the doubly linked list
def getTail(self):
return self.tail
# Function to set the tail of the doubly linked list
def setTail(self, tail):
self.tail = tail
# Function to replace Kth node from beginning with Kth node from end
def swapNode(self, headReference, tailReference, 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:
self.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
nodeCount = self.getCount(headReference)
if k == nodeCount:
self.swapFirstAndLast(headReference, tailReference)
return
# If the Kth node from the beginning and Kth node from the ending are same
if 2 * k - 1 == nodeCount:
return
# fNode represents Kth node from the beginning
fNode = headReference
for i in range(1, k):
fNode = fNode.next
fNodePrevious = fNode.previous
fNodeNext = fNode.next
# sNode represents Kth node from the ending
sNode = tailReference
for i in range(1, k):
sNode = sNode.previous
sNodePrevious = sNode.previous
sNodeNext = sNode.next
# Checking if any of the pointers is null and interchanging the pointers
if fNodePrevious != None and sNode != None:
fNodePrevious.next = sNode
sNode.previous = fNodePrevious
sNode.next = fNodeNext
fNodeNext.previous = sNode
if sNodePrevious != None and sNodeNext != None:
sNodeNext.previous = fNode
fNode.next = sNodeNext
sNodePrevious.next = fNode
fNode.previous = sNodePrevious
# Function to swap the first and last node in the doubly linked list
def swapFirstAndLast(self, headReference, tailReference):
headRef = headReference
tailRef = tailReference
headReference = headReference.next
tailReference = tailReference.previous
tailReference.next = headRef
headRef.previous = tailReference
headRef.next = None
self.setTail(tailReference.next)
headReference.previous = tailRef
tailRef.next = headReference
tailRef.previous = None
self.setHead(headReference.previous)
# Function to return the number of nodes in the linked list
def getCount(self, headReference):
nodeCount = 0
while headReference != None:
nodeCount += 1
headReference = headReference.next
return nodeCount
# Function to insert a node at
# the end of the doubly linked list
def push(self, data):
newNode = Node(data)
if (self.head == None):
self.head = self.tail = newNode
else:
self.tail.setNext(newNode)
newNode.setPrevious(self.tail)
self.tail = newNode
def printList(self, headReference):
if headReference == None:
print("Doubly linked list is empty")
return
while headReference:
print(headReference.data,end = ' ')
headReference = headReference.next
print()
# Driver code
# Creating an object for the class
list = 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
K = 2
list.swapNode(list.getHead(),list.getTail(), K)
list.printList(list.getHead())
C#
// 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
JavaScript
// Node structure for the doubly linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.previous = null;
}
}
// Class for the doubly linked list
class DoublyLinkedList {
constructor() {
this.head = null; // head of the doubly linked list
this.tail = null; // tail of the doubly linked list
}
// Function to add a node at the end of the doubly linked list
push(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = this.tail = newNode;
} else {
newNode.previous = this.tail;
this.tail.next = newNode;
this.tail = newNode;
}
}
// Function to return the number of nodes in the linked list
getCount() {
let nodeCount = 0;
let currentNode = this.head;
while (currentNode !== null) {
nodeCount++;
currentNode = currentNode.next;
}
return nodeCount;
}
// Function to swap the first and last node in the doubly linked list
swapFirstAndLast() {
const headRef = this.head;
const tailRef = this.tail;
this.head = this.head.next;
this.tail = this.tail.previous;
this.tail.next = headRef;
headRef.previous = this.tail;
headRef.next = null;
this.tail.next = tailRef;
tailRef.previous = this.tail;
tailRef.next = null;
}
// Function to swap Kth node from the beginning with Kth node from the end
swapNode(K) {
// If K is 1, then the first node has to be swapped with the last node
if (K === 1) {
this.swapFirstAndLast();
return;
}
// If K is N, then the last node has to be swapped with the first node
const nodeCount = this.getCount();
if (K === nodeCount) {
this.swapFirstAndLast();
return;
}
// If the Kth node from the beginning and Kth node from the end are the same
if (2 * K - 1 === nodeCount) {
return;
}
// Find the Kth node from the beginning
let fNode = this.head;
for (let i = 1; i < K; i++) {
fNode = fNode.next;
}
const fNodePrevious = fNode.previous;
const fNodeNext = fNode.next;
// Find the Kth node from the end
let sNode = this.tail;
for (let i = 1; i < K; i++) {
sNode = sNode.previous;
}
const sNodePrevious = sNode.previous;
const sNodeNext = sNode.next;
// Interchange the pointers
if (fNodePrevious !== null && sNode !== null) {
fNodePrevious.next = sNode;
sNode.previous = fNodePrevious;
sNode.next = fNodeNext;
fNodeNext.previous = sNode;
}
if (sNodePrevious !== null && sNodeNext !== null) {
sNodeNext.previous = fNode;
fNode.next = sNodeNext;
sNodePrevious.next = fNode;
fNode.previous = sNodePrevious;
}
}
// Function to print the doubly linked list
// Function to print the doubly linked list
printList() {
if (!this.head) {
console.log("Doubly linked list is empty");
} else {
let currentNode = this.head;
let output = "";
while (currentNode !== null) {
output += currentNode.data + " ";
currentNode = currentNode.next;
}
console.log(output.trim());
}
}
}
// Create an instance of the DoublyLinkedList class
const linkedList = new DoublyLinkedList();
// Add data to the linked list
linkedList.push(1);
linkedList.push(2);
linkedList.push(3);
linkedList.push(4);
linkedList.push(5);
// Call the function to swap the Kth node (e.g., K = 2)
const K = 2;
linkedList.swapNode(K);
// Print the linked list after the swap
linkedList.printList();
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:
- Make the list as a circular linked list
- Change the previous pointer of the first node to the last but one node (20 in example figure)
- Change the next pointer of last but one node to the last node. In this case it will be 60.
- After swapping, make the head as the first node.
Consider p and q are the nodes which are to be swapped,
head = q; //change head pointer to point to head node
last = p; //change last pointer to point to last node
swapping first and last nodesCase 2: Swapping the ordinary Kth node from the beginning and Kth node from the end.
Steps:
- Let us consider K = 2. So the nodes to be swapped or interchanged are 20 and 50 as show in the figure.
- 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 caseCase 3: Swapping the middle nodes
Steps:
- 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).
- Consider p is the first node to be swapped and q is the second node to be swapped.
- 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.
- In the same way, point the first pointer of next node of q to the previous node of q.
- Change the links of p and q so that both the nodes points to the previous node of p (step2 in the below figure).
- Make the links of p and q accordingly to make the nodes swap their positions.
To swap middle nodesImplementation:
C++
// CPP program to swap Kth node from beginning with
// the Kth node from the end without using temporary
// node and without swapping the data
#include <bits/stdc++.h>
using namespace std;
// class Node
class Node {
public:
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*& head, Node*& last)
{
Node* temp = new Node(data);
if (!head) {
head = temp;
last = temp;
}
else {
last->next = temp;
temp->first = last;
last = temp;
}
}
// function for printing the doubly linked list
void printList(Node* head)
{
Node* p = head;
while (p) {
cout << p->data << "<->";
p = p->next;
}
cout << "NULL" << endl;
}
// function for swapping Kth node from
// beginning with Kth node from the end
void swapKthNodes(Node*& head, Node*& last, 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
int main()
{
// 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 calls for inserting
// at the end of the list
AddLast(10, head, last);
AddLast(20, head, last);
AddLast(30, head, last);
AddLast(40, head, last);
AddLast(50, head, last);
AddLast(60, head, last);
cout << "Before swapping:" << endl;
// print list before swapping the nodes
printList(head);
cout << endl;
// function call for swapping Kth nodes
swapKthNodes(head, last, 1);
cout << "After swapping nodes for k = 1:" << endl;
// print list after swapping the nodes
printList(head);
cout << endl;
swapKthNodes(head, last, 2);
cout << "After swapping nodes for k = 2:" << endl;
printList(head);
cout << endl;
swapKthNodes(head, last, 3);
cout << "After swapping nodes for k = 3 (middle):"
<< endl;
printList(head);
cout << endl;
return 0;
}
// This code is contributed Tapesh(tapeshdua420)
Java
// Java program to swap Kth node from beginning with
// the Kth node from the end without using temporary
// node and without swapping the data
public 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 Node
class 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 function
if __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 data
using 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
// Javascript code
class Node {
constructor(data) {
this.data = data;
this.first = null;
this.next = null;
}
}
// function for inserting new node at the
// end of the list using last pointer
function AddLast(data, head, last) {
let temp = new Node(data);
if (!head) {
head = temp;
last = temp;
}
else {
last.next = temp;
temp.first = last;
last = temp;
}
return [head, last];
}
// function for printing the doubly linked list
function printList(head) {
let p = head;
while (p) {
console.log(`${p.data}<->`);
p = p.next;
}
console.log("NULL");
}
// function for swapping Kth node from
// beginning with Kth node from the end
function swapKthNodes(head, last, k) {
let count = 1;
let 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;
return [head, last];
}
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;
}
}
return [head, last];
}
// Driver function
// head pointer for pointing to start of the linked list
// last pointer for pointing to last node of the linked
// list
let head = null, last = null;
// function calls for inserting
// at the end of the list
[head, last] = AddLast(10, head, last);
[head, last] = AddLast(20, head, last);
[head, last] = AddLast(30, head, last);
[head, last] = AddLast(40, head, last);
[head, last] = AddLast(50, head, last);
[head, last] = AddLast(60, head, last);
console.log("Before swapping:");
// print list before swapping the nodes
printList(head);
console.log();
// function call for swapping Kth nodes
[head, last] = swapKthNodes(head, last, 1);
console.log("After swapping nodes for k = 1:");
// print list after swapping the nodes
printList(head);
console.log();
[head, last] = swapKthNodes(head, last, 2);
console.log("After swapping nodes for k = 2:");
printList(head);
console.log();
[head, last] = swapKthNodes(head, last, 3);
console.log("After swapping nodes for k = 3 (middle):");
printList(head);
console.log();
// This code is contributed by akashish__
OutputBefore 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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem