Question

In: Computer Science

THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a...

THIS QUESTION IS BASED UPON JAVA PROGRAMMING.

Exercise 1 In this exercise, you will add a method swapNodes to SinglyLinkedList class. This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same nodes, etc. Write the main method to test the swapNodes method. Hint: You may need to traverse the list.

Exercise 2 In this exercise, you will use the DoublyLinkedList implementation of the textbook. Write a method for concatenating two doubly-linked lists L and M, with header and trailer sentinel nodes, into a single list L′. Write a main method to test the new method. Hint: Connect the end of L into the beginning of M.

Solutions

Expert Solution

Exercise 1 :

In Exercise 1, first we have to check if two nodes are equal then don't need to swap. Otherwise, first find the node1 from the linkedlist and store the prev and curr node and same for node2 then after swap the nodes. If the any node is not present then swapping is not possible for two nodes.

sawapTwoNodes() method will swap the two nodes of the linkedlist.

Program:-

public class SinglyLinkedList {
    
    class Node {
        
        // LinkedList node contain integer
        public int item;
        
        // points to the next node
        public Node next;
        
        // prarameterized constructor which create new node for the linkedlist
        public Node(int item){
            
            this.item = item;
            this.next = null;
        }
        
        // prarameterized constructor which add a node with the linkedlist
        public Node(int item, Node next){
            
            this.item = item;
            this.next = next;
        }
    }
    
    // it will point to the head node of the linked list
    private Node head;
    
    // add node at the head of linked list
    public void addFirst(int a){
        
        // add newNode as a head node
        head = new Node(a, head);
    }
    
    
    // This method print the whole linkedlist
    public void printList(){
        
        Node node = head; 
        while (node != null) 
        { 
            // print last node without aerrow
            if(node.next == null)
                System.out.print(node.item); 
            else
                System.out.print(node.item+" -> "); 
            
            node = node.next; 
        } 
    }
    
    // This method will swap the node if they are present in the linkedlist
    public void swapTwoNodes(int node1, int node2){
        
        // if two nodes are equal then dont need to swap that nodes
        if(node1 == node2){
            System.out.println("\nBoth Nodes are equal");
            return;
        }
        
        // search node1 from the linkedlist and save prev and curr node
        Node prevNode1 = null, currNode1 = head; 
        while (currNode1 != null && currNode1.item != node1) 
        { 
            // store previous node
            prevNode1 = currNode1; 
            
            // go to the next node
            currNode1 = currNode1.next; 
        } 
  
        // search node 2 from the linkedlist and save prev and curr node
        Node prevNode2 = null, currNode2 = head; 
        while (currNode2 != null && currNode2.item != node2) 
        { 
            // store previous node
            prevNode2 = currNode2;
            
            // go to the next node
            currNode2 = currNode2.next; 
        } 
  
        // check whether node1 and node2 are present or not? 
        if (currNode1 == null || currNode2 == null){
            
            if(currNode1 == null)
                System.out.println("\n"+node1+" is not present in the linkedlist");
            
            if(currNode2 == null)
                System.out.println("\n"+node2+" is not present in the linkedlist");
            
            System.out.println("Sorry! Swapping is not possible");
            return;
        } 
            
  
        // If node1 is not head of linked list 
        if (prevNode1 != null){
            // prev node point to the node2
            prevNode1.next = currNode2; 
        }
        else{
            // otherwise create node2 as a head 
            head = currNode2; 
        }
  
        // If node2 is not head of linked list 
        if (prevNode2 != null){ 
            // prev node point to the node1
            prevNode2.next = currNode1; 
        }
        else{
            // otherwise create node1 as a head 
            head = currNode1; 
        }
  
        // Now Swap next pointers only  
        Node temp = currNode1.next; 
        currNode1.next = currNode2.next; 
        currNode2.next = temp; 
        
    }
    
    /*
        main() method test the swapNodes() method.
    */
    public static void main(String[] args) {
        
        SinglyLinkedList list = new SinglyLinkedList();
        
        // add fisrt node to the linked list
        list.addFirst(40);
        list.addFirst(30);
        list.addFirst(20);
        list.addFirst(10);
        
        System.out.println("\nLinked list before calling swapTwoNodes(nod1, node2): "); 
        list.printList(); 
  
        list.swapTwoNodes(20, 20); 
  
        System.out.println();
        
        System.out.println("\nLinked list after calling swapTwoNodes(node1, node2): "); 
        list.printList(); 
        
        System.out.println();
    }
}

Output :-

1> When both nodes are present

2> When both nodes are not present

3> When both nodes are equal

Exercise 2 :

In exercise 2, we will concatenate two doubly linkedlist where end of the first linked list will point to the head of second linked list.

concatenateTwoDoublyLinkedList() method will concatenate the two doublylinkedlist.

Program :-

public class DoublyLinkedList {    

    //This class repersents node for doubly linked list
    class Node{  
        
        // instance members for doubly linked list
        int item;  
        Node prev;  
        Node next;  
   
        //constructor for doubly linked list
        public Node(int item) {  
            this.item = item;  
        }  
    }  
    
    //Initially, heade and last is set to null
    Node head, last;  
   
    
    // This method addNode at the end of the doubly linked list
    public void addNodeAtTheEnd(int item) { 
        
        //Create a new node  
        Node newNode = new Node(item);  
   
        //if list is empty, head and last points to newNode  
        if(head == null) {  
            
            head = last = newNode;  
            
            //head's prev will be null  
            head.prev = null;  
            
            //last's next will be null  
            last.next = null;  
        }  
        else {  
            
            //add newNode to the end of list. last->next set to newNode  
            last.next = newNode;  
            
            //set new node prev as a last  
            newNode.prev = last;  
            
            //newNode becomes new last  
            last = newNode;  
            
            //last next will be null  
            last.next = null;  
        }  
    }  
   
    // This method will print the doubly linkedlist
    public void printList(){
        
        Node node = head; 
        while (node != null) 
        { 
            // print last node without aerrow
            if(node.next == null)
                System.out.print(node.item); 
            else
                System.out.print(node.item+" -> "); 
            
            node = node.next; 
        } 
    }
    
    public void concatenateTwoDoublyLinkedList(DoublyLinkedList list2){
        
        // if list2 is null then return;
        if(list2.head == null)
            return;
        
        // store head of the list2
        Node list2Head = list2.head;
        
        // if list1 is null then create list2 as a list1
        if(this.head == null){
            
            // store head to the first doublylinkedlist
            this.head = list2Head;
            return;
        }
        
        // now store the head to the next of last node of first doubly linked list
        this.last.next = list2Head;
        
        // connect last node of first doublylinkedlist with the head of second doubly linkedlist
        list2Head.prev = this.last;
        
        System.out.println("\nConcatenation Of Two DoublyLinkedList successful");
    }
    
    /*
        main() method test the concatenationTwoDoublyLinkedList() method.
    */
    public static void main(String[] args) {  
        
        //create first DoublyLinkedList object
        DoublyLinkedList dll1 = new DoublyLinkedList();  
        
        // add node into the first doubly linkedlist
        dll1.addNodeAtTheEnd(10);
        dll1.addNodeAtTheEnd(20);
        dll1.addNodeAtTheEnd(30);
        dll1.addNodeAtTheEnd(40);
        
        //create second DoublyLinkedList object
        DoublyLinkedList dll2 = new DoublyLinkedList();  
        
        // add node into the second doubly linkedlist
        dll2.addNodeAtTheEnd(50);
        dll2.addNodeAtTheEnd(60);
        dll2.addNodeAtTheEnd(70);
        dll2.addNodeAtTheEnd(80);
        
        // display first linkedlist
        System.out.println("\nFirst DoublyLinkedList : ");
        dll1.printList();
        
        // display second linkedlist
        System.out.println("\nSecond DoublyLinkedList : ");
        dll2.printList();
        
        // concatenate above two linkedlist
        dll1.concatenateTwoDoublyLinkedList(dll2);
        
        // print concatenated doublylinkedlist
        System.out.println("\nConcatenated DoublyLinkedList");
        dll1.printList();
        
        System.out.println();
    }  
}

Output:-


I mentioned the printList() method in above two Exercise (1 & 2) which will print the whole linkedlist.

I hope you will understand above two programs.

Do you feel needful and useful then please upvote me.

Thank you.


Related Solutions

Lab # 4 Multidimensional Arrays Please write in JAVA. Programming Exercise 8.5 (Algebra: add two matrices)...
Lab # 4 Multidimensional Arrays Please write in JAVA. Programming Exercise 8.5 (Algebra: add two matrices) Write a method to add two matrices. The header of the method is as follows: public static double[][] addMatrix(double[][] a, double[][] b In order to be added, the two matrices must have the same dimensions and the same or compatible types of elements. Let c be the resulting matrix. Each element cij is aij + bij. For example, for two 3 * 3 matrices...
IN JAVA: Repeat Exercise 28, but add the methods to the LinkedStack class. Add the following...
IN JAVA: Repeat Exercise 28, but add the methods to the LinkedStack class. Add the following methods to the LinkedStacked class, and create a test driver for each to show that they work correctly. In order to practice your array related coding skills, code each of these methods by accessing the internal variables of the LinkedStacked, not by calling the previously defined public methods of the class. - String toString()—creates and returns a string that correctly represents the current stack....
1. Based upon the pseudocode given in “Background”, solve the three versions of add up to...
1. Based upon the pseudocode given in “Background”, solve the three versions of add up to K problems: ◦ all pairs of numbers that add up to K ◦ all triples (set of three) that add up to K ◦ all possible subsets of numbers that add up to K: recursive version is given, you are asked to solve it iteratively. 2. Test the three functions using given test cases. 3. Measure the running time of algorithms under various input...
JAVA programming language Please add or modify base on the given code Adding functionality Add functionality...
JAVA programming language Please add or modify base on the given code Adding functionality Add functionality for multiplication (*) Adding JUnit tests Add one appropriately-named method to test some valid values for tryParseInt You will use an assertEquals You'll check that tryParseInt returns the expected value The values to test: "-2" "-1" "0" "1" "2" Hint: You will need to cast the return value from tryParseInt to an int e.g., (int) ValidationHelper.tryParseInt("1") Add one appropriately-named method to test some invalid...
Question Objective: The objective of this lab exercise is to give you practice in programming with...
Question Objective: The objective of this lab exercise is to give you practice in programming with one of Python’s most widely used “container” data types -- the List (commonly called an “Array” in most other programming languages). More specifically you will demonstrate how to: Declare list objects Access a list for storing (i.e., writing) into a cell (a.k.a., element or component) and retrieving (i.e., reading) a value from a list cell/element/component Iterate through a list looking for specific values using...
In JAVA Language Please! Programming Exercise 3.20 required you to design a PID manager that allocated...
In JAVA Language Please! Programming Exercise 3.20 required you to design a PID manager that allocated a unique process identifier to each process. Exercise 4.20 required you to modify your solution to Exercise 3.20 by writing a program that created a number of threads that requested and released process identifiers. Now modify your solution to Exercise 4.20 by ensuring that the data structure used to represent the availability of process identifiers is safe from race conditions. Use Pthreads mutex locks....
java Programming Problem 1: Reverse Characters Create an application ReverseCharacters in which you use an array-based...
java Programming Problem 1: Reverse Characters Create an application ReverseCharacters in which you use an array-based stack to read a sentence from the keyboard, and reverse the order of the letters in each word. Print the initial sentence, as well as the result of the reversal operation. Your Tasks: Using the information given in your textbook, create a class named ArrayBasedStack, that will help you solve the problem given above by providing the stack operations you need for this application....
this a continuation of my previous question. answer with Java programming language and Netbeans idk 1,...
this a continuation of my previous question. answer with Java programming language and Netbeans idk 1, 2, 3, 4) CODE class Device { private String serialNumber, color, manufacturer; private double outputPower; public Device () { serialNumber = ""; color = ""; manufacturer = ""; outputPower = 0.0; } public Device(String serialNumber, String color, String manufacturer, double outputPower) { this.serialNumber = serialNumber; this.color = color; this.manufacturer = manufacturer; this.outputPower = outputPower; } public String getSerialNumber() { return serialNumber; } public void...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only run if the account status is active. You can do this adding a Boolean data member ‘active’ which describes account status (active or inactive). A private method isActive should also be added to check ‘active’ data member. This data member is set to be true in the constructor, i.e. the account is active the first time class Account is created. Add another private method...
Please answer the following question: 1) Based upon the knowledge relating to fraud examination and the...
Please answer the following question: 1) Based upon the knowledge relating to fraud examination and the fraud triangle, “Understand the Person, Understand the Fraud” concept, means to you. 2) Discuss how you, a fraud examiner, would approach and conduct an interview of a fraud suspect(s) in a case you have been assigned. Remember to include techniques, theory and approaches in your answer. Make sure your answer demonstrates your understanding of the fraud triangle and fraud examination.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT