Question

In: Computer Science

class LinkListTest { public static void main(String[] args) { LinkList theList = new LinkList(); theList.insertFirst(7); theList.insertFirst(6);...

class LinkListTest
{
    public static void main(String[] args)
    {
        LinkList theList = new LinkList();
        theList.insertFirst(7);
        theList.insertFirst(6);
        theList.insertFirst(5);
        theList.insertFirst(4);
        theList.insertFirst(3);
        theList.insertFirst(2);
        theList.insertFirst(1);

        theList.displayList();
        System.out.println("delete(4)");
        theList.delete(4);

        System.out.println("delete(16)");
        theList.delete(16);

        theList.displayList(); 

        System.out.println("insertAfter(2, 12)");
        theList.insertAfter(2, 12);

        System.out.println("insertAfter(4, 14)");
        theList.insertAfter(4, 14);

        System.out.println("insertAfter(7, 17)");
        theList.insertAfter(7, 17);

        theList.displayList();

        System.out.println("insertLast(20)");
        theList.insertLast(20);

        theList.displayList();

    } 
} 
class Link
{
    public int iData;              // data item
    public Link next;              // next link in list
    // -------------------------------------------------------------
    public Link(int id)             // constructor
    {
        iData = id;                 // initialize data
        next = null;
    }                           
    // -------------------------------------------------------------
    public void displayLink()      // display ourself
    {
        System.out.print(iData +" ");
    }
}  // end class Link
public class LinkList
{
    private Link first;            // ref to first item on list
    // -------------------------------------------------------------
    public LinkList()              // constructor
    { 
        first = null; 
    }           // no items on list yet
    // -------------------------------------------------------------
    public boolean isEmpty()       // true if list is empty
    { 
        return (first==null); 
    }
    // -------------------------------------------------------------
    public void insertFirst(int dd) // insert at start of list
    {                           // make new link
        Link newLink = new Link(dd);
        newLink.next = first;       // newLink --> old first
        first = newLink;            // first --> newLink
    }
    // -------------------------------------------------------------
    public Link deleteFirst()      // delete first item
    {                           // (assumes list not empty)
        Link temp = first;          // save reference to link
        first = first.next;         // delete it: first-->old next
        return temp;          // return deleted link
    }
    // -------------------------------------------------------------
    public void displayList()
    {
        Link current = first;       // start at beginning of list
        while(current != null)      // until end of list,
        {
            current.displayLink();   // print data
            current = current.next;  // move to next link
        }
        System.out.println("");
    }
    // -------------------------------------------------------------
}  // end class LinkList

For methods find and delete the return type is Link not key. The method returns a Link object.

Add these methods to the provided LinkList class:

1-     Key find(int key) returns the link with the specified key or null if not found.

2-     void insertAfter(int afterKey, int newKey) inserts a new link with key newKey after the node with key afterKey. If the afterKey node does not exist, the method just returns. Must call method find(int key).

3-     Key delete(int key) removes and returns the Link with the specified key if the node exists, returns null otherwise.

4-     Link getLast() returns a reference to the last link in the list.

5-     void insertLast(int key) adds a new node with the specified key to the end of the list. Must call method getLAst().

Use LinkListTest.java to test your code.

Solutions

Expert Solution

class Main 
{ 
    Node head;  // head of list 
  
    /* Linked list Node*/
    class Node 
    { 
        int data; 
        Node next; 
        Node(int d) {data = d; next = null; } 
    } 
  
    /* This function is in LinkedList class. Inserts a 
   new Node at front of the list. This method is  
   defined inside LinkedList class shown above */
    public void insertFirst(int new_data) 
    { 
        /* 1 & 2: Allocate the Node & 
                  Put in the data*/
        Node new_node = new Node(new_data); 
      
        /* 3. Make next of new Node as head */
        new_node.next = head; 
      
        /* 4. Move the head to point to new Node */
        head = new_node; 
    } 
  
    /* Inserts a new node after the given prev_node. */
    public void insertAfterUtil(Node prev_node, int new_data) 
    { 
        /* 1. Check if the given Node is null */
        if (prev_node == null) 
        { 
            System.out.println("The given previous node cannot be null"); 
            return; 
        } 
  
        /* 2 & 3: Allocate the Node & 
                  Put in the data*/
        Node new_node = new Node(new_data); 
  
        /* 4. Make next of new Node as next of prev_node */
        new_node.next = prev_node.next; 
  
        /* 5. make next of prev_node as new_node */
        prev_node.next = new_node; 
    } 
    
    public void insertAfter(int afterKey,int newKey){
        Node node = head;
        Node prevNode = null;
        while( node != null ){
            if( node.data == afterKey ){
                prevNode = node;   
            } 
            node = node.next;
        }
        if( prevNode == null ){
            return;
        }
        insertAfterUtil(prevNode,newKey);
    }
     
    /* Appends a new node at the end.  This method is  
       defined inside LinkedList class shown above */
    public void insertLast(int new_data) 
    { 
        /* 1. Allocate the Node & 
           2. Put in the data 
           3. Set next as null */
        Node new_node = new Node(new_data); 
  
        /* 4. If the Linked List is empty, then make the 
              new node as head */
        if (head == null) 
        { 
            head = new Node(new_data); 
            return; 
        } 
  
        /* 4. This new node is going to be the last node, so 
              make next of it as null */
        new_node.next = null; 
  
        /* 5. Else traverse till the last node */
        Node last = head;  
        while (last.next != null) 
            last = last.next; 
  
        /* 6. Change the next of last node */
        last.next = new_node; 
        return; 
    } 
  
    /* This function prints contents of linked list starting from 
        the given node */
    public void displayList() 
    { 
        Node tnode = head; 
        while (tnode != null) 
        { 
            System.out.print(tnode.data+" "); 
            tnode = tnode.next; 
        } 
    } 
    
    /* Given a key, deletes the first occurrence of key in linked list */
    void delete(int key)
    {
        // Store head node
        Node temp = head, prev = null;
 
        // If head node itself holds the key to be deleted
        if (temp != null && temp.data == key)
        {
            head = temp.next; // Changed head
            return;
        }
 
        // Search for the key to be deleted, keep track of the
        // previous node as we need to change temp.next
        while (temp != null && temp.data != key)
        {
            prev = temp;
            temp = temp.next;
        }    
 
        // If key was not present in linked list
        if (temp == null) return;
 
        // Unlink the node from linked list
        prev.next = temp.next;
    }
  
    /* Driver program to test above functions. Ideally this function 
       should be in a separate user class.  It is kept here to keep 
       code compact */
    public static void main(String[] args) 
    { 
        /* Start with the empty list */
        Main llist = new Main(); 
        llist.insertFirst(7); 
        llist.insertFirst(6); 
        llist.insertFirst(5); 
        llist.insertFirst(4); 
        llist.insertFirst(3); 
        llist.insertFirst(2); 
        llist.insertFirst(1);
        llist.displayList(); 
        
        llist.insertAfter(7, 8); 
        System.out.println("\ndelete(4) "); 
        llist.delete(4);
        System.out.println("\ndelete(16) "); 
        llist.delete(16);
        llist.displayList(); 

        System.out.println("\ninsertAfter(2, 12)");
        llist.insertAfter(2, 12);

        System.out.println("insertAfter(4, 14)");
        llist.insertAfter(4, 14);

        System.out.println("insertAfter(7, 17)");
        llist.insertAfter(7, 17);

        llist.displayList();

        System.out.println("\ninsertLast(20)");
        llist.insertLast(20);

        llist.displayList();
    } 
} 

Output:


Related Solutions

public class OOPExercises {     public static void main(String[] args) {         A objA = new...
public class OOPExercises {     public static void main(String[] args) {         A objA = new A();         B objB = new B();         System.out.println("in main(): ");         System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());         objA.setA (222);         objB.setB (333.33);       System.out.println("objA.a = "+objA.getA());         System.out.println("objB.b = "+objB.getB());     } } Output: public class A {     int a = 100;     public A() {         System.out.println("in the constructor of class A: ");         System.out.println("a = "+a);         a =...
Consider this program: public class Main { public static void main(String[] args) { String s1 =...
Consider this program: public class Main { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); System.out.println(s1 == s2); System.out.println(s2 == s3); System.out.println(s2.equals(s3)); } } When we run the program, the output is: true false true Explain why this is the output, using words and/or pictures.
public class Main { public static void main(String [] args) { int [] array1 = {5,...
public class Main { public static void main(String [] args) { int [] array1 = {5, 8, 34, 7, 2, 46, 53, 12, 24, 65}; int numElements = 10; System.out.println("Part 1"); // Part 1 // Enter the statement to print the numbers in index 5 and index 8 // put a space in between the two numbers and a new line at the end // Enter the statement to print the numbers 8 and 53 from the array above //...
---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { int[] A = {11, 12,...
---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { int[] A = {11, 12, -10, 13, 9, 12, 14, 15, -20, 0}; System.out.println("The maximum is "+Max(A)); System.out.println("The summation is "+Sum(A)); } static int Max(int[] A) { int max = A[0]; for (int i = 1; i < A.length; i++) { if (A[i] > max) { max = A[i]; } } return max; } static int Sum(int[] B){ int sum = 0; for(int i = 0; i --------------------------------------------------------------------------------------------------------------------------- Convert...
public class Main{ public static void main (String[] args) { Map<Integer, String> ssnMap = new HashMap<Integer,...
public class Main{ public static void main (String[] args) { Map<Integer, String> ssnMap = new HashMap<Integer, String>(); ssnMap.put (8675309,"Jenney"); ssnMap.put (42, "Answer to Everything"); ssnMap.put (8675309, "Stacy"); ssnMap.put (1006, "Peter"); System.out.println(ssnMap.get (8675309)); } } What is the output of the above code. Why?
class Main { public static void main(String[] args) {        int[] array = {1,2,3,4,5};   ...
class Main { public static void main(String[] args) {        int[] array = {1,2,3,4,5};        //Complexity Analysis //Instructions: Print the time complexity of method Q1_3 with respect to n=Size of input array. For example, if the complexity of the //algorithm is Big O nlogn, add the following code where specified: System.out.println("O(nlogn)"); //TODO }    public static void Q1_3(int[] array){ int count = 0; for(int i = 0; i < array.length; i++){ for(int j = i; j < array.length;...
public class GreeterTest {    public static void main(String[] args)    { // create an object...
public class GreeterTest {    public static void main(String[] args)    { // create an object for Greeter class Greeter greeter = new Greeter("Jack"); // create two variables Greeter var1 = greeter; Greeter var2 = greeter; // call the sayHello method on the first Greeter variable String res1 = var1.sayHello(); System.out.println("The first reference " + res1); // Call the setName method on the secod Grreter variable var2.setName("Mike"); String res2 = var2.sayHello(); System.out.println("The second reference " + res2);    } }...
public class ArraySkills { public static void main(String[] args) { // *********************** // For each item...
public class ArraySkills { public static void main(String[] args) { // *********************** // For each item below you must code the solution. You may not use any of the // methods found in the Arrays class or the Collections classes // You must use Java's built-in Arrays. You are welcome to use the Math and/or Random class if necessary. // You MUST put your code directly beneath the comment for each item indicated. String[] myData; // 1. Instantiate the given...
------------------------------------------------------------------------------------ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input =...
------------------------------------------------------------------------------------ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int result = 0; System.out.print("Enter the first number: "); int x = input.nextInt(); System.out.print("Enter the second number: "); int y = input.nextInt(); System.out.println("operation type for + = 0"); System.out.println("operation type for - = 1"); System.out.println("operation type for * = 2"); System.out.print("Enter the operation type: "); int z = input.nextInt(); if(z==0){ result = x + y; System.out.println("The result is " + result); }else...
public class StackTest { public static void main(String[] args) { StackX theStack = new StackX(10); //...
public class StackTest { public static void main(String[] args) { StackX theStack = new StackX(10); // make new stack theStack.push(20); // push items onto stack theStack.push(30); theStack.push(40); theStack.push(40); theStack.push(60); theStack.push(80); theStack.showStack(); System.out.println("removeDownTo(40)"); theStack.removeDownTo(40); theStack.showStack(); } // end main() } public class QueueTest { public static void main(String[] args) { Queue theQueue = new Queue(20); // queue holds 5 items theQueue.insert(10); // insert 4 items theQueue.insert(20); theQueue.insert(30); theQueue.insert(40); theQueue.showQueue(); System.out.println("Removing 3 items"); theQueue.remove(); // remove 3 items theQueue.remove(); // (10, 20,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT