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...
I am struggling with this assignment for my java class. Objectives: Your program will be graded...
I am struggling with this assignment for my java class. Objectives: Your program will be graded according to the rubric below. Please review each objective before submitting your work so you don’t lose points. 1.Create a new project and class in Eclipse and add the main method. (5 points) 2. Construct a Scanner to read input from the keyboard. (5 points) 3. Prompt the user with three questions from the Psychology Today quiz, and use the Scanner to read their...
I have been working on this assignment in Java programming and can not get it to...
I have been working on this assignment in Java programming and can not get it to work. This method attempts to DECODES an ENCODED string without the key.    public static void breakCodeCipher(String plainText){ char input[]plainText.toCharArray(); for(int j=0; j<25; j++){ for(int i=0; i<input.length; i++) if(input[i]>='a' && input[i]<='Z') input[i]=(char)('a'+((input[i]-'a')+25)%26); else if(input[i]>='A'&& input[i]<='Z') input[i]=(char)('A'+ ((input[i]-'A')+25)%26); } System.out.println(plainText)    }
Java File I/O Assignment: 1. Write a generic LinkedList class referencing page 2 and page 3....
Java File I/O Assignment: 1. Write a generic LinkedList class referencing page 2 and page 3. a. The class must be named LinkedList. b. The class must provide the methods listed above for constructing, accessing, and manipulating LinkedList objects for a generic type. c. Other than for testing purposes, the LinkedList class should do no input or output. d. The package must enable the provided tests. 2. Test this class using JUnit. a. A suite of JUnit tests have been...
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...
Strategic Versus Deep Learning The class that I took that I have to exercise strategic learner...
Strategic Versus Deep Learning The class that I took that I have to exercise strategic learner in order to pass a test is Chemistry, which happened to be a virtual learning and I basically have to do both the lab aspect of it online too and that was so hard for me, but I focused on one goal which is passing the class with a good grade. When it comes to surface learning, most of the time, we are unable...
**JAVA LANGUAGE** This assignment will use the Employee class that you developed for assignment 6. Design...
**JAVA LANGUAGE** This assignment will use the Employee class that you developed for assignment 6. Design two sub- classes of Employee...FullTimeEmployee and HourlyEmployee. A full-time employee has an annual salary attribute and may elect to receive life insurance. An hourly employee has an hourly pay rate attribute, an hours worked attribute for the current pay period, a total hours worked attribute for the current year, a current earnings attribute (for current pay period), a cumulative earnings attribute (for the current...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT