Exchange first and last nodes in Circular Linked List

Suppose we are inserted the following (1,3,5,2,6,7) node in a sequence.

Before swap first and last nodes After swap first and last nodes

Here given code implementation process.

//C Program 
//Exchange first and last nodes in Circular Linked List
#include<stdio.h>
#include <stdlib.h> //for malloc function

//Create structure
struct Node{
  int data;
  struct Node*next;
};
//function prototype
void insert(struct Node**,int);
void display(struct Node*);
void swap_node(struct Node**);
//insert Node element at end of linked list
void insert(struct Node**head,int value){
  //Create dynamic node
  struct Node*node=(struct Node*)malloc(sizeof(struct Node));
  if(node==NULL){
    printf("Memory overflow\n");
  }else{
    node->data=value;
    node->next=*head;
    if(*head==NULL){
      *head=node;
      node->next=*head;
    }else{
      struct Node*temp=*head;
      while(temp->next!=*head){
        temp=temp->next;
      }
      //Add node at last position
      temp->next=node;
    }
  }
}
//Display element of Node
void display(struct Node*head){
  
  if(head==NULL){
    printf("Empty linked list");
  }
  else{
    printf("\n Linked List Element :");
    struct Node*temp=head;
    while(temp){
      printf("  %d",temp->data);
      temp=temp->next;
      if(temp==head){
        break; //terminate loop
      }
    }

  }
}
//Swap or exchange first and last nodes
void swap_node(struct Node**head){
  if(*head==NULL){
    printf("Empty linked list");
  }
  else{
      
    struct Node*temp=*head,*first=*head,*prev=*head;
    if(temp->next==NULL){
      //not circular linked list
      return;
    }else if(temp->next==temp){
      //only onle element of linked list
      printf("\n Only One element of linked list");
      return;
    }

    while(temp!=NULL && temp->next!=*head){
      prev=temp;
      temp=temp->next;
    }
    if(prev==*head){
      //only two element in this linked list
      *head=prev->next;
    }else{
      //that is last node
      temp=prev->next;
      //modified link 
      temp->next=first->next;
      prev->next=*head;
      first->next=temp;
      //make last node to head
      *head=temp;
    }

  }
}
int main(){

  //create node pointer
  struct Node*head=NULL;
  //insert element of linked list
  insert(&head,1);
  insert(&head,3);
  insert(&head,5);
  insert(&head,2);
  insert(&head,6);
  insert(&head,7);
 
  printf("\n Before Exchange");
  //display all node
  display(head);

  printf("\n After Exchange");
  swap_node(&head);
  //display all node
  display(head);
}

Output

 Before Exchange
 Linked List Element :  1  3  5  2  6  7
 After Exchange
 Linked List Element :  7  3  5  2  6  1
//C++ Program 
//Exchange first and last nodes in circular linked list
#include<iostream>
using namespace std;

//create structure
struct Node{
  int data;
  struct Node*next;
};
class CircularList{
  Node *head;
public:
  CircularList();
  void insert(int);
  void display();
  void swap_node();
};
CircularList::CircularList(){
  head=NULL;
}

//insert Node at end of linked list 
void CircularList:: insert(int value){
  //Create dynamic node
  struct Node*node=new Node;
  if(node==NULL){
    cout<<"Memory overflow"<<endl;
  }else{
    node->data=value;
    node->next=head;
    if(head==NULL){
      //when linked list empty
      head=node;
      node->next=head;
    }else{
      Node*temp=head;
      //find last node
      while(temp->next!=head){
        temp=temp->next;
      }
      //Add node at last
      temp->next=node;
    }
  }
}
//display element of Node
void CircularList:: display(){
  
  if(head==NULL){
    cout<<"Empty linked list";
  }
  else{
    cout<<"\nElement of linked list :";
    struct Node*temp=head;
    while(temp){
      cout<<"  "<<temp->data;
      temp=temp->next;
      if(temp==head){
        break; //terminate loop
      }
    }

  }
}
//Swap or exchange first and last nodes
void CircularList:: swap_node(){
  if(head==NULL){
    cout<<"Empty linked list"<<endl;
  }
  else{
      
    struct Node*temp=head,*first=head,*prev=head;
    if(temp->next==NULL){
      //not circular linked list
      return;
    }else if(temp->next==temp){
      //only onle element of linked list
      cout<<"Only One element of linked list";
      return;
    }

    while(temp!=NULL && temp->next!=head){
      prev=temp;
      temp=temp->next;
    }
    if(prev==head){
      //only two element in this linked list
      head=prev->next;
    }else{
      //that is last node
      temp=prev->next;
      //modified link 
      temp->next=first->next;
      prev->next=head;
      first->next=temp;
      //make last node to head
      head=temp;
    }

  }
}
int main(){
  CircularList obj=CircularList();
  //insert element of linked list
  obj.insert(1);
  obj.insert(3);
  obj.insert(5);
  obj.insert(2);
  obj.insert(6);
  obj.insert(7);
  cout<<"Before Exchange"<<endl;
  //display all node
  obj.display();
  cout<<"\nAfter Exchange"<<endl;
  obj.swap_node();
  obj.display();
}

Output

Before Exchange

Element of linked list :  1  3  5  2  6  7
After Exchange

Element of linked list :  7  3  5  2  6  1
//Java Program to 
//Exchange first and last nodes in circular linked list
public class LinkedList{
  static class Node{
    int data;
    Node next;
  }
  static Node head;
    //Class constructors
  LinkedList(){
    head=null;
  } 
    //insert node at last of linke list
  static void insert(int value){
      //Create a node
    Node node=new Node();
    node.data=value;
    node.next=head;
    if(head==null){
      head=node;
      node.next=head;
    }
    else{
      Node temp=head;
          //find lase node
      while(temp.next!=head){
        temp=temp.next;
      }
          //add node
      temp.next=node;
    }

  }
    //Display node element of circular linked list
  public static void display(){
    if(head==null){
      System.out.println("Empty Linked List");
    }else{
      System.out.print("Circular Linked List Element :");
      Node temp=head;
      while(temp!=null){
        System.out.print("  "+temp.data);
        temp=temp.next;
        if(temp==head) break;
      }
    }
  }
  public static void swapNode(){
    if(head==null){
      System.out.println("Empty linked list");
    }
    else{

      Node temp=head, first=head, prev=head;
      if(temp.next==null){
            //not circular linked list
        return;
      }else if(temp.next==temp){
            //only onle element of linked list
        System.out.println("Only One element of linked list");
        return;
      }

      while(temp!=null && temp.next!=head){
        prev=temp;
        temp=temp.next;
      }
      if(prev==head){
            //only two element in this linked list
        head=prev.next;
      }else{
            //that is last node
        temp=prev.next;
            //modified link 
        temp.next=first.next;
        prev.next=head;
        first.next=temp;
            //make last node to head
        head=temp;
      }

    }
  }
  public static void main(String[] args) {
    LinkedList obj=new LinkedList();
    //insert element of linked list
    obj.insert(1);
    obj.insert(3);
    obj.insert(5);
    obj.insert(2);
    obj.insert(6);
    obj.insert(7);
    
    System.out.println("Before Exchange");
    obj.display();
    System.out.println("\nAfter Exchange");
    obj.swapNode();
    obj.display();
  }
}

Output

Before Exchange
Circular Linked List Element :  1  3  5  2  6  7
After Exchange
Circular Linked List Element :  7  3  5  2  6  1

Output

#Python Program
#Exchange first and last nodes in circular linked list
class Node:
    def __init__(self,data):
        self.data=data
        self.next=None

#create class CircularList    
class CircularList:
    def __init__(self):
        #Assign default value
        self.head=None

    #Insert new node to End of Linked list  
    def insert(self,data):
        node=Node(data)
        node.next=self.head
        if(self.head==None):
            #when no element of linked list
            self.head=node
            node.next=node
        else:
            temp=self.head
            while(temp.next!=self.head):
                temp=temp.next
            #add node    
            temp.next=node    
    #display all element of circular linked list      
    def display(self):
        if(self.head==None):
            print("Empty Linked List")
            return

        temp=self.head
        print("Linked list Elements : ")
        while(temp!=None):
            print(temp.data)
            temp=temp.next
            #when find first node
            if(temp==self.head):
                break

        print("\n")

    #exchange first and last element of circular linked list     
    def swapNodes(self):
        if(self.head==None):
            print("Empty Linked List")
        else:
          temp=self.head
          prev=self.head
          first=self.head
          if(temp.next==None or temp.next==self.head):
            print("Only One Element in this Linked List")
          else:
            while(temp!=None and temp.next!=self.head):
              prev=temp  #hold address
              temp=temp.next 

            if(prev==self.head):
              self.head=prev.next
            else:
              temp=prev.next #hold last node
              temp.next=first.next
              prev.next=first
              first.next=temp
              self.head=temp #last node make head 


def main():
    #Create Object of class CircularList
    obj=CircularList()
    #Insert element
    obj.insert(1)
    obj.insert(3)
    obj.insert(5)
    obj.insert(2)
    obj.insert(6)
    obj.insert(7)
    print("Before Exachange")
    obj.display()
    print("After Exachange")
    obj.swapNodes()    
    obj.display()
if __name__ == '__main__':
    main()
After Exchange first and last Node
//C# program 
//Exchange first and last nodes in Circular Linked List
using System;
//node class
public class Node{
  public  int data;
  public  Node next;
}
class Program
{
  public Node head;
  public Program(){
    head=null;
  }
  //insert node of linked list
  public void insert(int data){
    Node newNode=new Node();
    newNode.data=data;
    newNode.next=head;
    if(head==null){
      //when no element of linked list
      head=newNode;
      newNode.next=head;
    }
    else{
      Node temp=head;
      //get last node
      while(temp.next!=head ){
        temp=temp.next;
      }
      //add new node
      temp.next=newNode;
    }
  }
  //Display element of linked list
  public void display(){
    if(head==null){
      Console.Write("Empty Linked List");
    }else{
      Console.Write(" Circular Linked List : ");
      Node temp=head;
      while(temp!=null){
        Console.Write(" {0}",temp.data);
        temp=temp.next;
        //End of Loop iteration 
        if(temp==head) break;
      }
    }
  }
  //Exchange First and Last Node
  public  void swapNode(){
    if(head==null){
      Console.Write("\nEmpty linked list");
    }
    else{

      Node temp=head, first=head, prev=head;
      if(temp.next==null){
        //not circular linked list
        return;
      }else if(temp.next==temp){
        //only onle element of linked list
        Console.Write("\nOnly One element of linked list\n");
        return;
      }

      while(temp!=null && temp.next!=head){
        prev=temp;
        temp=temp.next;
      }
      if(prev==head){
            //only two element in this linked list
        head=prev.next;
      }else{
            //that is last node
        temp=prev.next;
            //modified link 
        temp.next=first.next;
        prev.next=head;
        first.next=temp;
            //make last node to head
        head=temp;
      }

    }
  }
  static void Main(){

    Program obj=new Program();
   //insert element of linked list
    obj.insert(1);
    obj.insert(3);
    obj.insert(5);
    obj.insert(2);
    obj.insert(6);
    obj.insert(7);
    
    Console.Write("Before Exchange");
    obj.display();
    Console.Write("\nAfter Exchange");
    obj.swapNode();
    obj.display();
  }
}

Output

Before Exchange Circular Linked List :  1 3 5 2 6 7
After Exchange Circular Linked List :  7 3 5 2 6 1


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved