Question

In: Computer Science

This is a JAVA assignment and i dont have the SinglyLinkedList class   Exercise 1 In this...

This is a JAVA assignment and i dont have the SinglyLinkedList class  

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 node, 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.

Thanks

Solutions

Expert Solution

Exercise 1 Solution:

import java.util.Scanner;
class Node 
{ 
        int data; 
        Node next; 
        Node(int t) 
        { 
                data = t; 
                next = null; 
        } 
} 

public class LinkedList 
{ 
        Node head;
        public void swapNodes(int x, int y) 
        { 
                //There is nothing to do if x and y are same 
                if (x == y) return; 
                Node previous_X = null, current_X = head; 
                while (current_X != null && current_X.data != x) 
                { 
                        previous_X = current_X; 
                        current_X = current_X.next; 
                } 
                Node previous_Y = null, current_Y = head; 
                while (current_Y != null && current_Y.data != y) 
                { 
                        previous_Y = current_Y; 
                        current_Y = current_Y.next; 
                } 

                // If either x or y is not present, nothing to do 
                if (current_X == null || current_Y == null) 
                        return; 
                        
                if (previous_X != null) 
                        previous_X.next = current_Y; 
                else 
                        head = current_Y; 

                if (previous_Y != null) 
                        previous_Y.next = current_X; 
                else 
                        head = current_X; 

                //Swapping the next pointers 
                Node temp = current_X.next; 
                current_X.next = current_Y.next; 
                current_Y.next = temp; 
        } 

        public void push(int new_data) 
        { 
            
                Node new_Node = new Node(new_data); 

                new_Node.next = head; 

                head = new_Node; 
        } 
        public void printList() 
        { 
                Node tNode = head; 
                while (tNode != null) 
                { 
                        System.out.print(tNode.data+" "); 
                        tNode = tNode.next; 
                } 
        } 

    //Main function to test the code
        public static void main(String[] args) 
        { 
            Scanner sc=new Scanner(System.in);
                LinkedList llist = new LinkedList(); 
                System.out.println("Enter the values that are need to pushed into list(by space separated values)");
            String str=sc.nextLine();
            String s[]=str.split(" ");
            for(int i=s.length-1;i>=0;i--){
                llist.push(Integer.parseInt(s[i]));
            }

                System.out.println("Enter any two node values that you want to swap");
                System.out.print("Node 1 value:");
                int N1=sc.nextInt();
                System.out.print("Node 2 value:");
                int N2=sc.nextInt();

                System.out.print("\n Linked list before calling swapNodes() (before swapping): "); 
                llist.printList(); 

                llist.swapNodes(N1, N2); 

                System.out.print("\n Linked list after calling swapNodes() (after swapping):   "); 
                llist.printList(); 
        } 
} 

Exercise 2 solution:

import java.util.*;

class Node 
{
        int data;
        Node next;
        Node(int t) {data = t;
                                next = null;}
}
        
public class MergeLists 
{
Node head; 

public void addToTheLast(Node node) 
{
        if (head == null)
        {
                head = node;
        }
        else
        {
                Node temp = head;
                while (temp.next != null)
                        temp = temp.next;
                temp.next = node;
        }
}

void printList()
{
        Node temp = head;
        while (temp != null)
        {
                System.out.print(temp.data + " ");
                temp = temp.next;
        } 
        System.out.println();
}


public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
        MergeLists llist1 = new MergeLists();
        MergeLists llist2 = new MergeLists();
        System.out.println("Enter two lists that are to be merged(by space separated vales)");
        System.out.print("Enter List 1:");
        String str1=sc.nextLine();
            String s1[]=str1.split(" ");
        System.out.print("Enter List 2:");
            String str2=sc.nextLine();
            String s2[]=str2.split(" ");
            for(int i=0,j=0;i<s1.length&&j<s2.length;i++,j++){
                llist1.addToTheLast(new Node(Integer.parseInt(s1[i])));
                llist2.addToTheLast(new Node(Integer.parseInt(s2[j])));
            }
        
        
        llist1.head = new Gfg().sortedMerge(llist1.head, 
                                                                                llist2.head);
        llist1.printList();      
        
}
}

class Gfg
{
Node sortedMerge(Node headA, Node headB)
{
        Node dummyNode = new Node(0);
        
        Node tail = dummyNode;
        while(true) 
        {
                if(headA == null)
                {
                        tail.next = headB;
                        break;
                }
                if(headB == null)
                {
                        tail.next = headA;
                        break;
                }
                
                if(headA.data <= headB.data)
                {
                        tail.next = headA;
                        headA = headA.next;
                } 
                else
                {
                        tail.next = headB;
                        headB = headB.next;
                }
                tail = tail.next;
        }
        return dummyNode.next;
}
}

Thank you!, if you have any queries post it below in the comment section i will try my best to resolve your queries and if required i will add them to my code.


Related Solutions

I have the following code for my java class assignment but i am having an issue...
I have the following code for my java class assignment but i am having an issue with this error i keep getting. On the following lines: return new Circle(color, radius); return new Rectangle(color, length, width); I am getting the following error for each line: "non-static variable this cannot be referenced from a static context" Here is the code I have: /* * ShapeDemo - simple inheritance hierarchy and dynamic binding. * * The Shape class must be compiled before the...
I have this exercise and i dont know how to do it DDB Corporation was formed...
I have this exercise and i dont know how to do it DDB Corporation was formed by twenty-four shareholders on January 1, 2017. The shareholders will be having their semi-annual meeting on September 28, 2018 to review the financial results for January 1 – June 30, 2018. As of January 1, 2018, the company has a retained deficit (this means the company incurred a net loss in 2017). The following are the unadjusted balances of DDB Corporation as of June...
Class Exercise: Constructor using JAVA Let’s define a Class together and have a constructor while at...
Class Exercise: Constructor using JAVA Let’s define a Class together and have a constructor while at it. - What should the Class object represent? (What is the “real life object” to represent)? - What properties should it have? (let’s hold off on the methods/actions for now – unless necessary for the constructor) - What should happen when a new instance of the Class is created? - Question: What are you allowed to do in the constructor? - Let’s test this...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
I have the following assignment for probability class: I am supposed to write a routine (code)...
I have the following assignment for probability class: I am supposed to write a routine (code) in MATLAB that does solve the following problem for me: a) Generate N=10000 samples of a Uniform random variable (X) using the rand () command. This Uniform RV should have a range of -1 to +3. b) Generate (Estimate) and plot the PDF of X from the samples. You are not allowed to use the Histogram () command, any commands from the Matlab Statistics...
in Java please For this assignment you are to write a class that supports the addition...
in Java please For this assignment you are to write a class that supports the addition of extra long integers, by using linked-lists. Longer than what is supported by Java's built-in data type, called long. Your program will take in two strings, consisting of only digits, covert each of them to a linked-list that represents an integer version on that string. Then it will create a third linked-list that represents the sum of both of the linked lists. Lastly, it...
For my economy class I need to annswer these questions but I just dont get/cant find...
For my economy class I need to annswer these questions but I just dont get/cant find the right inf. The Presentville – Futureville case: 1. Explain what motivated each group to make the decisions they made.
JAVA CODE BEGINNERS, I already have the DEMO CLASS(NEED YOU TO USE), I need you to...
JAVA CODE BEGINNERS, I already have the DEMO CLASS(NEED YOU TO USE), I need you to use all methods, also switch statements. Write a Temperature class. The class will have three conversion methods: toCelsius(), toKelvin() and toFahrenheit(). These methods will return a Temperature in those three scales equal to the this temperature. Note that the value of this is not changed in these conversions. In addition to these three conversion methods the class will have methods add(Temperature), subtract(Temperature), multiply(Temperature), and...
0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
java For this assignment, you will create a Time class that holds an hour value and...
java For this assignment, you will create a Time class that holds an hour value and a minute value to represent a time. We will be using "military time", so 12:01 AM is 0001 and 1 PM is 1300. For this assignment, you may assume valid military times range from 0000 to 2359. Valid standard times range from 12:00 AM to 11:59 PM. In previous assignments, we had a requirement that your class be named Main. In this assignment, the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT