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

The following SinglyLinkedList class is available: class SinglyLinkedList: class _Node: """Lightweight, nonpublic class for storing a...
The following SinglyLinkedList class is available: class SinglyLinkedList: class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = 'element', 'next' # streamline memory usage def __init__(self, element, next): # initialize node's fields self.element = element # reference to user's element self.next = next # reference to next node def __init__(self): # initialize list's fields self._head = None # head references to None def printList(self, label): print(label, end=' ') curr = self._head while curr != None: print(curr.element, end="...
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...
Hi I have a java code for my assignment and I have problem with one of...
Hi I have a java code for my assignment and I have problem with one of my methods(slice).the error is Exception in thread "main" java.lang.StackOverflowError Slice method spec: Method Name: slice Return Type: Tuple (with proper generics) Method Parameters: Start (inclusive) and stop (exclusive) indexes. Both of these parameters are "Integer" types (not "int" types). Like "get" above, indexes may be positive or negative. Indexes may be null. Description: Positive indexes work in the normal way Negative indexes are described...
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) Balanced Class diagram: Balanced + swing(int[] a) : boolean For this exercise, you will have...
(JAVA) Balanced Class diagram: Balanced + swing(int[] a) : boolean For this exercise, you will have to implement the class diagram above. Basically, the objective of this exercise is to develop the class and the previous method, in such a way that it tells us if an array is balanced or not. We say that an array is balanced if the sum of the elements belonging to the first half of the array (not including the element in the middle),...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT