TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Program To Swap The Last Element Of The Singly Linked List From The First One

Program To Swap The Last Element Of The Singly Linked List From The First One on fibonacci, factorial, prime, armstrong, swap, reverse, search, sort, stack, queue, array, linkedlist, tree, graph etc.

<< Back to PROGRAM

Program to swap the last element of the singly linked list from the first one

Explanation

In this program we need to swap the last node of the singly linked list with the first node such that first node will become the last node and last node will become the first node.

Program to swap the last element of the singly linked list from the first one

Consider the above example; node 1 represents the head of the list and node 4 represent the last node. To swap the first node with the last node, we will iterate through the list such that index will point to second last node and current will point to the last node. Node temp will point to head. Then, make current (last node) as the new head of the list. Now, move the entire list after the old head and attach it after new head. Finally, add temp (old head node) after index node (second last node).

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class Swap which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail's next will point to a newly added node. This new node will become the new tail of the list.
  4. SwapFirstWithLast() will swap the first node with the last node:
    1. If the list is empty, return from the function.
    2. If the list is not empty, traverse through the list such that node current will point to the last node of the list and index will point to second last node.
    3. Check if the list contains only one node, then swapping is not possible.
    4. If the list contains only two nodes then, swap head node with current using node temp.
    5. Else, the temp will point to head, and current which was pointing to the last node will become the new head of the list.
    6. Move the list except for the old head node and attach it after new head, i.e. head.next = temp.next
    7. Now add the temp (first) node after index node to make it last node of the list and its next node will be null.
  5. display() will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

#Represent a node of the singly linked list
class Node:
    def __init__(self,data):
        self.data = data;
        self.next = None;
        
class Swap:
    #Represent the head of the singly linked list
    def __init__(self):
        self.head = None;
        
    #addNode() will add a new node to the list
    def addNode(self, data):
        #Create a new node
        newNode = Node(data);
        
        #Checks if the list is empty
        if(self.head == None):
            #If list is empty, head will point to new node
            self.head = newNode;
        else:
            current = self.head;
            while(current.next != None):
                current = current.next;
            #newNode will be added after last node of the list
            current.next = newNode;
            
    #swapLastWithFirst() will swap head node with the last node of the list
    def swapLastWithFirst(self):
        current = self.head;
        temp = None;
        index = None;
        
        #If list is empty, then display the list as it is
        if(self.head == None):
            return;
        else:
            #After the loop, current will point to last element and index will point to second last element
            while(current.next != None):
                index = current;
                current = current.next;
                
            #If list contains only one node, then display list as it is
            if(self.head == current):
                return;
                
            #If list contains only two nodes, then swap the head node with current node
            elif(self.head.next == current):
                temp = self.head;
                #head will point to last node i.e. current
                self.head = current;
                #node next to new head will be the last node
                self.head.next = temp;
                #Node next to last element will be None
                temp.next = None;
            else:
                temp = self.head;
                #head will point to last node i.e. current
                self.head = current;
                #Detach the list from previous head and add it after new head
                self.head.next = temp.next;
                #Previous head will become last node of the list
                index.next = temp;
                #Node next to last element will be None
                temp.next = None;
            
    #display() will display all the nodes present in the list
    def display(self):
        #Node current will point to head
        current = self.head;
        
        if(self.head == None):
            print("List is empty");
            return;
        while(current != None):
            #Prints each node by incrementing pointer
            print(current.data ),
            current = current.next;
        print "";
 
sList = Swap();
        
#Add nodes to the list
sList.addNode(1);
sList.addNode(2);
sList.addNode(3);
sList.addNode(4);
 
print("Originals list: ");
sList.display();
 
#Swaps Last node with first node
sList.swapLastWithFirst();
 
print("List after swapping the first node with last: ");
sList.display();

Output:

 Originals list: 
1 2 3 4 
List after swapping the first node with last:
4 2 3 1 

C

#include <stdio.h>
 
//Represent a node of the singly linked list
struct node{
    int data;
    struct node *next;
};    
 
//Represent the head of the singly linked list
struct node *head = NULL;
 
//addNode() will add a new node to the list
void addNode(int data) {
    //Create a new node
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = NULL;
    
    //Checks if the list is empty
    if(head == NULL) {
        //If list is empty, head will point to new node
        head = newNode;
    }
    else {
        struct node *current = head;
        while(current->next != NULL) {
            current = current->next;
        }
        //newNode will be added after last node of the list
        current->next = newNode;
    }
}
 
//swapLastWithFirst() will swap head node with the last node of the list
void swapLastWithFirst() {
    struct node *current = head, *temp = NULL, *index = NULL;
    
    //If list is empty, then display the list as it is
    if(head == NULL) {
        return;
    }
    else {
        //After the loop, current will point to last element and index will point to second last element
        while(current->next != NULL) {
            index = current;
            current = current->next;
        }
        
        //If list contains only one node, then display list as it is
        if(head == current) {
            return;
        }
        //If list contains only two nodes, then swap the head node with current node
        else if(head->next == current) {
            temp = head;
            //head will point to last node i.e. current
            head = current;
            //node next to new head will be the last node
            head->next = temp;
            //Node next to last element will be null
            temp->next = NULL;
        }
        else {
            temp = head;
            //head will point to last node i.e. current
            head = current;
            //Detach the list from previous head and add it after new head
            head->next = temp->next;
            //Previous head will become last node of the list
            index->next = temp;
            //Node next to last element will be null
            temp->next = NULL;
        }
    }
}
    
//display() will display all the nodes present in the list
void display() {
    //Node current will point to head
    struct node *current = head;
    
    if(head == NULL) {
        printf("List is empty\n");
        return;
    }
    while(current != NULL) {
        //Prints each node by incrementing pointer
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}
    
int main()
{
    //Add nodes to the list
    addNode(1);
    addNode(2);
    addNode(3);
    addNode(4);
 
    printf("Originals list: \n");
    display();
    
    //Swaps Last node with first node
    swapLastWithFirst();
    
    printf("List after swapping the first node with last: \n");
    display();
 
    return 0;
}

Output:

Originals list: 
1 2 3 4 
List after swapping the first node with last:
4 2 3 1 

JAVA

public class Swap {
    
    //Represent a node of the singly linked list
    class Node{
        int data;
        Node next;
        
        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
 
    //Represent the head of the singly linked list
    public Node head = null;
    
    //addNode() will add a new node to the list
    public void addNode(int data) {
        //Create a new node
        Node newNode = new Node(data);
        
        //Checks if the list is empty
        if(head == null) {
            //If list is empty, head will point to new node
            head = newNode;
        }
        else {
            Node current = head;
            while(current.next != null) {
                current = current.next;
            }
            //newNode will be added after last node of the list
            current.next = newNode;
        }
    }
    
    //swapLastWithFirst() will swap head node with the last node of the list
    public void swapLastWithFirst() {
        Node current = head, temp = null, index = null;
        
        //If list is empty, then display the list as it is
        if(head == null) {
            return;
        }
        else {
            //After the loop, current will point to last element and index will point to second last element
            while(current.next != null) {
                index = current;
                current = current.next;
            }
            
            //If list contains only one node, then display list as it is
            if(head == current) {
                return;
            }
            //If list contains only two nodes, then swap the head node with current node
            else if(head.next == current) {
                temp = head;
                //head will point to last node i.e. current
                head = current;
                //node next to new head will be the last node
                head.next = temp;
                //Node next to last element will be null
                temp.next = null;
            }
            else {
                temp = head;
                //head will point to last node i.e. current
                head = current;
                //Detach the list from previous head and add it after new head
                head.next = temp.next;
                //Previous head will become last node of the list
                index.next = temp;
                //Node next to last element will be null
                temp.next = null;
            }
        }
    }
    
    //display() will display all the nodes present in the list
    public void display() {
        //Node current will point to head
        Node current = head;
        if(head == null) {
            System.out.println("List is empty");
            return;
        }
        while(current != null) {
            //Prints each node by incrementing pointer
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        
        Swap sList = new Swap();
        
        //Add nodes to the list
        sList.addNode(1);
        sList.addNode(2);
        sList.addNode(3);
        sList.addNode(4);
 
        System.out.println("Originals list: ");
        sList.display();
        
        //Swaps Last node with first node
        sList.swapLastWithFirst();
        
        System.out.println("List after swapping the first node with last: ");
        sList.display();
    }
}

Output:

Originals list: 
1 2 3 4 
List after swapping the first node with last:
4 2 3 1 

C#

using System;
                    
public class CreateList
{
    //Represent a node of the singly linked list
    public class Node<T>{
        public T data;
        public Node<T> next;
        
        public Node(T value) {
            data = value;
            next = null;
        }
    }
        
    public class Swap<T>{
        //Represent the head of the singly linked list
        public Node<T> head = null;             
    
        //addNode() will add a new node to the list
        public void addNode(T data) {
            //Create a new node
            Node<T> newNode = new Node<T>(data);
 
            //Checks if the list is empty
            if(head == null) {
                //If list is empty, head will point to new node
                head = newNode;
            }
            else {
                Node<T> current = head;
                while(current.next != null) {
                    current = current.next;
                }
                //newNode will be added after last node of the list
                current.next = newNode;
            }
        }
        
        //swapLastWithFirst() will swap head node with the last node of the list
        public void swapLastWithFirst() {
            Node<T> current = head, temp = null, index = null;
 
            //If list is empty, then display the list as it is
            if(head == null) {
                return;
            }
            else {
                //After the loop, current will point to last element and index will point to second last element
                while(current.next != null) {
                    index = current;
                    current = current.next;
                }
 
                //If list contains only one node, then display list as it is
                if(head == current) {
                    return;
                }
                //If list contains only two nodes, then swap the head node with current node
                else if(head.next == current) {
                    temp = head;
                    //head will point to last node i.e. current
                    head = current;
                    //node next to new head will be the last node
                    head.next = temp;
                    //Node next to last element will be null
                    temp.next = null;
                }
                else {
                    temp = head;
                    //head will point to last node i.e. current
                    head = current;
                    //Detach the list from previous head and add it after new head
                    head.next = temp.next;
                    //Previous head will become last node of the list
                    index.next = temp;
                    //Node next to last element will be null
                    temp.next = null;
                }
            }
        }
        
        //display() will display all the nodes present in the list
        public void display() {
            //Node current will point to head
            Node<T> current = head;
            
            if(head == null) {
                Console.WriteLine("List is empty");
                return;
            }
            while(current != null) {
                //Prints each node by incrementing pointer
                Console.Write(current.data + " ");
                current = current.next;
            }
            Console.WriteLine();
        }
    }
    
    public static void Main()
    {
        Swap<int> sList = new Swap<int>();
        
        //Add nodes to the list
        sList.addNode(1);
        sList.addNode(2);
        sList.addNode(3);
        sList.addNode(4);
 
        Console.WriteLine("Originals list: ");
        sList.display();
        
        //Swaps Last node with first node
        sList.swapLastWithFirst();
        
        Console.WriteLine("List after swapping first node with last: ");
        sList.display();    
    }
}

Output:

Originals list: 
1 2 3 4 
List after swapping first node with last: 
4 2 3 1 

PHP

<!DOCTYPE html>
<html>
<body>
<?php
//Represent a node of singly linked list
class Node{
    public $data;
    public $next;
    
    function __construct($data){
        $this->data = $data;
        $this->next = NULL;
    }
}
class Swap{
    //Represent the head of the singly linked list
    public $head;
    function __construct(){
        $this->head = NULL;
    }
    
    //addNode() will add a new node to the list
    function addNode($data) {
        //Create a new node
        $newNode = new Node($data);
        
        //Checks if the list is empty
        if($this->head == NULL) {
            //If list is empty, head will point to new node
            $this->head = $newNode;
        }
        else {
            $current = $this->head;
            while($current->next != null) {
                $current = $current->next;
            }
            //newNode will be added after last node of the list
            $current->next = $newNode;
        }
    }
    
    //swapLastWithFirst() will swap head node with the last node of the list
    function swapLastWithFirst() {
        $current = $this->head;
        $temp = null;
        $index = null;
        
        //If list is empty, then display the list as it is
        if($this->head == null) {
            return;
        }
        else {
            //After the loop, current will point to last element and index will point to second last element
            while($current->next != null) {
                $index = $current;
                $current = $current->next;
            }
            
            //If list contains only one node, then display list as it is
            if($this->head == $current) {
                return;
            }
            //If list contains only two nodes, then swap the head node with current node
            else if($this->head->next == $current) {
                $temp = $this->head;
                //head will point to last node i.e. current
                $this->head = $current;
                //node next to new head will be the last node
                $this->head->next = $temp;
                //Node next to last element will be null
                $temp->next = null;
            }
            else {
                $temp = $this->head;
                //head will point to last node i.e. current
                $this->head = $current;
                //Detach the list from previous head and add it after new head
                $this->head->next = $temp->next;
                //Previous head will become last node of the list
                $index->next = $temp;
                //Node next to last element will be null
                $temp->next = null;
            }
        }
    }
    
    //display() will display all the nodes present in the list
    function display() {
        //Node current will point to head
        $current = $this->head;
        
        if($this->head == NULL) {
            print("List is empty <br>");
            return;
        }
        while($current != NULL) {
            //Prints each node by incrementing pointer
            print($current->data . " ");
            $current = $current->next;
        }
        print("<br>");
    }
}
    
$sList = new Swap();
        
//Add nodes to the list
$sList->addNode(1);
$sList->addNode(2);
$sList->addNode(3);
$sList->addNode(4);
 
print("Originals list: <br>");
$sList->display();
 
//Swaps Last node with first node
$sList->swapLastWithFirst();
 
print("List after swapping first node with last: <br>");
$sList->display();
?>
</body>
</html> 

Output:

Originals list: 
1 2 3 4 
List after swapping first node with last: 
4 2 3 1 

Next Topic#




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf