Question

In: Computer Science

Write a program to swap the first and last elements of a linked list. (i) by...

Write a program to swap the first and last elements of a linked list.

(i) by exchanging info part

(ii) through pointers

Need the program in java with no direct usage of packages use node and link.

Solutions

Expert Solution

A program to swap the first and last elements of a linked list

(i) by exchanging info part

class Swap {  // You can also use public keyword before class
      
    //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();  
    }  
}  

(ii) through pointers

NOTE:

  • Java doesn’t support pointer explicitly, But java uses pointer implicitly: Java use pointers for manipulations of references but these pointers are not available for outside use. Any operations implicitly done by the language are actually NOT visible.
// Java program to exchange  
// first and last node in  
// circular linked list 
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) 
{ 
    // 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); 
} 
} 

Related Solutions

Write a program to swap mth and nth elements of a linked list. User should give...
Write a program to swap mth and nth elements of a linked list. User should give input.
Write a C function to swap the first and last elements of an integer array. Call...
Write a C function to swap the first and last elements of an integer array. Call the function from main() with an int array of size 4. Print the results before and after swap (print all elements of the array in one line). The signature of the arrItemSwap() function is: void arrItemSwap(int *, int, int); /* array ptr, indices i, j to be swapped */ Submit the .c file. No marks will be given if your pgm does not compile...
Write a subroutine named swap in C thatswaps two nodes in a linked list. The first...
Write a subroutine named swap in C thatswaps two nodes in a linked list. The first node should not be able to change places. The nodes are given by: Struct nodeEl { int el; struct nodeEl * next; }; typdef struct nodeEl node; The list header (of type node *) is the first parameter of the subroutine. The second and third parameters consist of integers and are the places in the list where the nodes are to change places. The...
I need a MIPS Assembly program that "Display the elements of the linked list in reverse...
I need a MIPS Assembly program that "Display the elements of the linked list in reverse order." It needs subprogram and those subprogram does not have t registers.
1.Please write a C++ program that counts the nodes in a linked list with the first...
1.Please write a C++ program that counts the nodes in a linked list with the first node pointed to by first. Also please explain. 2. Write a program to determine the average of a linked list of real numbers with the first node pointed to by first. 3. Determine the computing times of the algorithms in question 1 and 4. Write a program to insert a new node into a linked list with the first node pointed to by first...
I need an example of how to swap and index within a doubly linked list with...
I need an example of how to swap and index within a doubly linked list with index + 1. This is written in java. public class A3DoubleLL<E> {    /*    * Grading:    * Swapped nodes without modifying values - 2pt    * Works for all special cases - 1pt    */    public void swap(int index) {        //swap the nodes at index and index+1        //change the next/prev connections, do not modify the values   ...
Write a java method to swap between two values in a singly linked list
Write a java method to swap between two values in a singly linked list
Write a c program Write a function to swap two elements of an integer array. Call...
Write a c program Write a function to swap two elements of an integer array. Call the function to swap the first element, i[0] with last element i[n], second element i[1] with the last but one element i[n-1] and so on. Should handle arrays with even and odd number of elements. Call the swap function with the following arrays and print results in each case before and after swapping. i. int arr1[] = {0, 1, 2, 3, 30, 20, 10,...
Find the last node of a linked list of n elements whose index is a multiple...
Find the last node of a linked list of n elements whose index is a multiple of k (counted from 0). For example, if the list is 12 → 75 → 37 → 99 → 12 → 38 → 99 → 60 ↓ and k = 4, then you should return the second 12 (with index 4). Your algorithm should take O(n) time and use O(1) extra space. Implement the following method in LinkedList.java. public T lastK(int k) LinkedList.java. public...
3. Find the last node of a linked list of n elements whose index is a...
3. Find the last node of a linked list of n elements whose index is a multiple of k (counted from 0). For example, if the list is 12 → 75 → 37 → 99 → 12 → 38 → 99 → 60 ↓ and k = 4, then it should return the second 12 (with index 4). The algorithm should take O(n) time and use O(1) extra space. Implement the following method in LinkedList.java. public T lastK(int k)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT