Exchange first and last nodes in Circular Linked List
Last Updated :
22 Feb, 2023
Given Circular linked list exchange the first and the last node. The task should be done with only one extra node, you can not declare more than one extra node, and also you are not allowed to declare any other temporary variable.
Note: Extra node means the need of a node to traverse a list.

Examples:
Input : 5 4 3 2 1
Output : 1 4 3 2 5
Input : 6 1 2 3 4 5 6 7 8 9
Output : 9 1 2 3 4 5 6 7 8 6
Method 1: (By Changing Links of First and Last Nodes)
We first find a pointer to the previous to the last node. Let this node be p. Now we change the next links so that the last and first nodes are swapped.
C++
// CPP program to exchange first and
// last node in circular linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
struct Node* addToEmpty(struct Node* head, int data)
{
// This function is only for empty list
if (head != NULL)
return head;
// Creating a node dynamically.
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp->data = data;
head = temp;
// Creating the link.
head->next = head;
return head;
}
struct Node* addBegin(struct Node* head, int data)
{
if (head == NULL)
return addToEmpty(head, data);
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = head->next;
head->next = temp;
return head;
}
/* function for traversing the list */
void traverse(struct Node* head)
{
struct Node* p;
// If list is empty, return.
if (head == NULL) {
cout << "List is empty." << endl;
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do {
cout << p->data << " ";
p = p->next;
} while (p != head);
}
/* Function to exchange first and last node*/
struct Node* exchangeNodes(struct Node* head)
{
// If list is of length 2
if (head->next->next == head) {
head = head->next;
return head;
}
// Find pointer to previous of last node
struct Node* p = head;
while (p->next->next != head)
p = p->next;
/* Exchange first and last nodes using
head and p */
p->next->next = head->next;
head->next = p->next;
p->next = head;
head = head->next;
return head;
}
// Driven Program
int main()
{
int i;
struct Node* head = NULL;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
cout << "List Before: ";
traverse(head);
cout << endl;
cout << "List After: ";
head = exchangeNodes(head);
traverse(head);
return 0;
}
Java
// Java program to exchange
// first and last node in
// circular linked list
import java.util.*;
import java.io.*;
public class GFG {
static class Node {
int data;
Node next;
};
static Node addToEmpty(Node head, int data)
{
// This function is only
// for empty list
if (head != null)
return head;
// Creating a node dynamically.
Node temp = new Node();
// Assigning the data.
temp.data = data;
head = temp;
// Creating the link.
head.next = head;
return head;
}
static Node addBegin(Node head, int data)
{
if (head == null)
return addToEmpty(head, data);
Node temp = new Node();
temp.data = data;
temp.next = head.next;
head.next = temp;
return head;
}
// function for traversing the list
static void traverse(Node head)
{
Node p;
// If list is empty, return.
if (head == null) {
System.out.print("List is empty.");
return;
}
// Pointing to first
// Node of the list.
p = head;
// Traversing the list.
do {
System.out.print(p.data + " ");
p = p.next;
} while (p != head);
}
// Function to exchange
// first and last node
static Node exchangeNodes(Node head)
{
// If list is of length 2
if (head.next.next == head) {
head = head.next;
return head;
}
// Find pointer to previous
// of last node
Node p = head;
while (p.next.next != head)
p = p.next;
// Exchange first and last
// nodes using head and p
p.next.next = head.next;
head.next = p.next;
p.next = head;
head = head.next;
return head;
}
// Driver Code
public static void main(String args[])
{
int i;
Node head = null;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
System.out.print("List Before: ");
traverse(head);
System.out.println();
System.out.print("List After: ");
head = exchangeNodes(head);
traverse(head);
}
}
// This code is contributed
// by Arnab Kundu
Python3
# Python3 program to exchange first and
# last node in circular linked list
import math
class Node:
def __init__(self, data):
self.data = data
self.next = None
def addToEmpty(head, data):
# This function is only for empty list
if (head != None):
return head
# Creating a node dynamically.
temp = Node(data)
# Assigning the data.
temp.data = data
head = temp
# Creating the link.
head.next = head
return head
def addBegin(head, data):
if (head == None):
return addToEmpty(head, data)
temp = Node(data)
temp.data = data
temp.next = head.next
head.next = temp
return head
# function for traversing the list
def traverse(head):
# If list is empty, return.
if (head == None):
print("List is empty.")
return
# Pointing to first Node of the list.
p = head
print(p.data, end=" ")
p = p.next
# Traversing the list.
while(p != head):
print(p.data, end=" ")
p = p.next
def exchangeNodes(head):
# Cases Handled: Linked List either empty or containing single node.
if head == None or head.next == head:
return head
# Cases Handled: Linked List containing only two nodes
elif head.next.next == head:
head = head.next
return head
# Cases Handled: Linked List containing multiple nodes
else:
prev = None
curr = head
temp = head
# finding last and second last nodes in linkedlist list
while curr.next != head:
prev = curr
curr = curr.next
# point the last node to second node of the list
curr.next = temp.next
# point the second last node to first node
prev.next = temp
# point the end of node to start ( make linked list circular )
temp.next = curr
# mark the starting of linked list
head = curr
return head
# Driver Code
if __name__ == '__main__':
head = None
head = addToEmpty(head, 6)
for x in range(5, 0, -1):
head = addBegin(head, x)
print("List Before: ", end="")
traverse(head)
print()
print("List After: ", end="")
head = exchangeNodes(head)
traverse(head)
# This code is contributed by Srathore
# Improved by Vinay Kumar (vinaykumar71)
C#
// C# program to exchange
// first and last node in
// circular linked list
using System;
public class GFG {
class Node {
public int data;
public Node next;
};
static Node addToEmpty(Node head, int data)
{
// This function is only
// for empty list
if (head != null)
return head;
// Creating a node dynamically.
Node temp = new Node();
// Assigning the data.
temp.data = data;
head = temp;
// Creating the link.
head.next = head;
return head;
}
static Node addBegin(Node head, int data)
{
if (head == null)
return addToEmpty(head, data);
Node temp = new Node();
temp.data = data;
temp.next = head.next;
head.next = temp;
return head;
}
// function for traversing the list
static void traverse(Node head)
{
Node p;
// If list is empty, return.
if (head == null) {
Console.Write("List is empty.");
return;
}
// Pointing to first
// Node of the list.
p = head;
// Traversing the list.
do {
Console.Write(p.data + " ");
p = p.next;
} while (p != head);
}
// Function to exchange
// first and last node
static Node exchangeNodes(Node head)
{
// If list is of length 2
if (head.next.next == head) {
head = head.next;
return head;
}
// Find pointer to previous
// of last node
Node p = head;
while (p.next.next != head)
p = p.next;
// Exchange first and last
// nodes using head and p
p.next.next = head.next;
head.next = p.next;
p.next = head;
head = head.next;
return head;
}
// Driver Code
public static void Main()
{
int i;
Node head = null;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
Console.Write("List Before: ");
traverse(head);
Console.WriteLine();
Console.Write("List After: ");
head = exchangeNodes(head);
traverse(head);
}
}
/* This code is contributed PrinciRaj1992 */
JavaScript
<script>
// javascript program to exchange
// first and last node in
// circular linked list
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
function addToEmpty(head , data) {
// This function is only
// for empty list
if (head != null)
return head;
// Creating a node dynamically.
var temp = new Node();
// Assigning the data.
temp.data = data;
head = temp;
// Creating the link.
head.next = head;
return head;
}
function addBegin(head , data) {
if (head == null)
return addToEmpty(head, data);
var temp = new Node();
temp.data = data;
temp.next = head.next;
head.next = temp;
return head;
}
// function for traversing the list
function traverse(head) {
var p;
// If list is empty, return.
if (head == null) {
document.write("List is empty.");
return;
}
// Pointing to first
// Node of the list.
p = head;
// Traversing the list.
do {
document.write(p.data + " ");
p = p.next;
} while (p != head);
}
// Function to exchange
// first and last node
function exchangeNodes(head) {
// If list is of length 2
if (head.next.next == head) {
head = head.next;
return head;
}
// Find pointer to previous
// of last node
var p = head;
while (p.next.next != head)
p = p.next;
// Exchange first and last
// nodes using head and p
p.next.next = head.next;
head.next = p.next;
p.next = head;
head = head.next;
return head;
}
// Driver Code
var i;
var head = null;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
document.write("List Before: ");
traverse(head);
document.write("<br/>");
document.write("List After: ");
head = exchangeNodes(head);
traverse(head);
// This code is contributed by umadevi9616
</script>
OutputList Before: 6 1 2 3 4 5
List After: 5 1 2 3 4 6
Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
Method 2: (By Swapping Values of First and Last nodes)
Algorithm:
- Traverse the list and find the last node(tail).
- Swap data of head and tail.
Below is the implementation of the algorithm:
C++
// CPP program to exchange first and
// last node in circular linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
struct Node* addToEmpty(struct Node* head, int data)
{
// This function is only for empty list
if (head != NULL)
return head;
// Creating a node dynamically.
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp->data = data;
head = temp;
// Creating the link.
head->next = head;
return head;
}
struct Node* addBegin(struct Node* head, int data)
{
if (head == NULL)
return addToEmpty(head, data);
struct Node* temp
= (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = head->next;
head->next = temp;
return head;
}
/* function for traversing the list */
void traverse(struct Node* head)
{
struct Node* p;
// If list is empty, return.
if (head == NULL) {
cout << "List is empty." << endl;
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do {
cout << p->data << " ";
p = p->next;
} while (p != head);
}
/* Function to exchange first and last node*/
struct Node* exchangeNodes(struct Node* head)
{
// If list is of length less than 2
if (head == NULL || head->next == NULL) {
return head;
}
Node* tail = head;
// Find pointer to the last node
while (tail->next != head) {
tail = tail->next;
}
/* Exchange first and last nodes using
head and p */
// temporary variable to store
// head data
int temp = tail->data;
tail->data = head->data;
head->data = temp;
return head;
}
// Driven Program
int main()
{
int i;
struct Node* head = NULL;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
cout << "List Before: ";
traverse(head);
cout << endl;
cout << "List After: ";
head = exchangeNodes(head);
traverse(head);
return 0;
}
Java
// JAVA program to exchange first and
// last node in circular linked list
import java.util.*;
import java.io.*;
public class GFG{
static class Node {
int data;
Node next;
};
static Node addToEmpty(Node head, int data)
{
// This function is only for empty list
if (head != null)
return head;
// Creating a node dynamically.
Node temp
= new Node();
// Assigning the data.
temp.data = data;
head = temp;
// Creating the link.
head.next = head;
return head;
}
static Node addBegin(Node head, int data)
{
if (head == null)
return addToEmpty(head, data);
Node temp
= new Node();
temp.data = data;
temp.next = head.next;
head.next = temp;
return head;
}
/* function for traversing the list */
static void traverse(Node head)
{
Node p;
// If list is empty, return.
if (head == null) {
System.out.print("List is empty." +"\n");
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do {
System.out.print(p.data+ " ");
p = p.next;
} while (p != head);
}
/* Function to exchange first and last node*/
static Node exchangeNodes(Node head)
{
// If list is of length less than 2
if (head == null || head.next == null) {
return head;
}
Node tail = head;
// Find pointer to the last node
while (tail.next != head) {
tail = tail.next;
}
/* Exchange first and last nodes using
head and p */
// temporary variable to store
// head data
int temp = tail.data;
tail.data = head.data;
head.data = temp;
return head;
}
// Driven Program
public static void main(String[] args)
{
int i;
Node head = null;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
System.out.print("List Before: ");
traverse(head);
System.out.println();
System.out.print("List After: ");
head = exchangeNodes(head);
traverse(head);
}
}
// This code is contributed by umadevi9616
Python3
# Python program to exchange first and
# last node in circular linked list class Node {
class Node:
def __init__(self):
self.data = 0
self.next = None
def addToEmpty(head, data):
# This function is only for empty list
if (head != None):
return head
# Creating a node dynamically.
temp = Node()
# Assigning the data.
temp.data = data
head = temp
# Creating the link.
head.next = head
return head
def addBegin(head, data):
if (head == None):
return addToEmpty(head, data)
temp = Node()
temp.data = data
temp.next = head.next
head.next = temp
return head
# function for traversing the list
def traverse(head):
# If list is empty, return.
if (head == None):
print("List is empty.")
return
# Pointing to first Node of the list.
p = head
# Traversing the list.
while (True):
print(p.data, end=" ")
p = p.next
if(p == head):
break
# Function to exchange first and last node
def exchangeNodes(head):
# If list is of length less than 2
if (head == None or head.next == None):
return head
tail = head
# Find pointer to the last node
while (tail.next != head):
tail = tail.next
# Exchange first and last nodes using head and p
# temporary variable to store
# head data
temp = tail.data
tail.data = head.data
head.data = temp
return head
# Driven Program
head = None
head = addToEmpty(head, 6)
for i in range(5, 0, -1):
head = addBegin(head, i)
print("List Before: ")
traverse(head)
print("")
print("List After: ")
head = exchangeNodes(head)
traverse(head)
# This code is contributed by Saurabh Jaiswal
C#
// C# program to exchange first and
// last node in circular linked list
using System;
public class GFG {
public class Node {
public int data;
public Node next;
};
static Node addToEmpty(Node head, int data) {
// This function is only for empty list
if (head != null)
return head;
// Creating a node dynamically.
Node temp = new Node();
// Assigning the data.
temp.data = data;
head = temp;
// Creating the link.
head.next = head;
return head;
}
static Node addBegin(Node head, int data) {
if (head == null)
return addToEmpty(head, data);
Node temp = new Node();
temp.data = data;
temp.next = head.next;
head.next = temp;
return head;
}
/* function for traversing the list */
static void traverse(Node head) {
Node p;
// If list is empty, return.
if (head == null) {
Console.Write("List is empty." + "\n");
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do {
Console.Write(p.data + " ");
p = p.next;
} while (p != head);
}
/* Function to exchange first and last node */
static Node exchangeNodes(Node head) {
// If list is of length less than 2
if (head == null || head.next == null) {
return head;
}
Node tail = head;
// Find pointer to the last node
while (tail.next != head) {
tail = tail.next;
}
/*
* Exchange first and last nodes using head and p
*/
// temporary variable to store
// head data
int temp = tail.data;
tail.data = head.data;
head.data = temp;
return head;
}
// Driven Program
public static void Main(String[] args) {
int i;
Node head = null;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
Console.Write("List Before: ");
traverse(head);
Console.WriteLine();
Console.Write("List After: ");
head = exchangeNodes(head);
traverse(head);
}
}
// This code is contributed by umadevi9616
JavaScript
<script>
// javascript program to exchange first and
// last node in circular linked list class Node {
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
function addToEmpty(head , data) {
// This function is only for empty list
if (head != null)
return head;
// Creating a node dynamically.
var temp = new Node();
// Assigning the data.
temp.data = data;
head = temp;
// Creating the link.
head.next = head;
return head;
}
function addBegin(head , data) {
if (head == null)
return addToEmpty(head, data);
var temp = new Node();
temp.data = data;
temp.next = head.next;
head.next = temp;
return head;
}
/* function for traversing the list */
function traverse(head) {
var p;
// If list is empty, return.
if (head == null) {
document.write("List is empty." + "\n");
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do {
document.write(p.data + " ");
p = p.next;
} while (p != head);
}
/* Function to exchange first and last node */
function exchangeNodes(head) {
// If list is of length less than 2
if (head == null || head.next == null) {
return head;
}
var tail = head;
// Find pointer to the last node
while (tail.next != head) {
tail = tail.next;
}
/*
* Exchange first and last nodes using head and p
*/
// temporary variable to store
// head data
var temp = tail.data;
tail.data = head.data;
head.data = temp;
return head;
}
// Driven Program
var i;
var head = null;
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
document.write("List Before: <br/>");
traverse(head);
document.write("<br/>");
document.write("List After: <br/>");
head = exchangeNodes(head);
traverse(head);
// This code is contributed by umadevi9616
</script>
OutputList Before: 6 1 2 3 4 5
List After: 5 1 2 3 4 6
Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
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