Question

urgent !! ASAP PLEASE DATA STRUCTURES To class SinglyLinkedList, add method afterThird(E e) which receives an...

urgent !! ASAP PLEASE

DATA STRUCTURES

To class SinglyLinkedList, add method afterThird(E e) which receives an element e and insert that in a new node after the third node in the list (assume the first node in the list is number 1). You should ensure that the linked list has at least three nodes, otherwise throw an exception. You should consider all possible cases.

Homework Answers

Answer #1
If you want the method to addatThird Plzz refer to method "insertAfterThird" in the below code:


public class LinkedList {
    private Node head; // head of list

    // Linked list Node.
    //  inner class is made to be static so that main() can access it
    static class Node {

        int data;
        Node next;

        // Constructor to add data in the list
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public static LinkedList insert(LinkedList list, int data) {
        // Create a new node with given data
        Node new_node = new Node(data);
        new_node.next = null;

        // If the Linked List is empty, then make the new node as head
        if (list.head == null) {
            list.head = new_node;
        } else {
            // Else traverse till the last node and insert the new_node there
            Node last = list.head;
            while (last.next != null) {
                last = last.next;
            }

            // Insert the new_node at last node
            last.next = new_node;
        }

        // Return the list by head
        return list;
    }


    // Method to print the LinkedList.
    public static void printList(LinkedList list) {
        Node currNode = list.head;

        System.out.print("LinkedList: ");

        // Traverse through the LinkedList
        while (currNode != null) {
            // Print the data at current node
            System.out.print(currNode.data + " ");

            // Go to next node
            currNode = currNode.next;
        }
        System.out.print("\n\n");
    }


    /**********************************************************
     * PROBLEM SOLUTION
     *Here is the solution to add at Third
     */


    //Method to find the length of linked list
    public static int getLength(LinkedList list) {

        //if list is null return 0
        if (list == null) return 0;

        //count variable to get count
        int count = 0;

        Node node = list.head;

        //traverse linked list until reach to end
        while (node != null) {
            count++;
            node = node.next;
        }

        //return length count
        return count;
    }


    public static void insertAfterThird(LinkedList list, int data) throws Exception {
        int lengthOfLinkedList = getLength(list);

        //if length is less than 3 throw exception 
        if (lengthOfLinkedList < 3) {
            throw new Exception("Linked List length is less than 3");
        }

        //generate new Node
        Node newNode = new Node(data);
        
        Node node = list.head;

        int count = 0;

        //traverse linked list and maintain count 
        while (node != null) {
            
            count++;
            
            // if count is equal to 3 insert the new node to it
            if (count == 3) {
                newNode.next = node.next;
                node.next = newNode;
            }
            node = node.next;
        }


    }

    /*******************************************************/

    public static void main(String[] args) {


        /* Start with the empty list. */
        LinkedList list = new LinkedList();
        /*Insertion to make Linked List of length 3*/
        list = insert(list, 1);
        list = insert(list, 2);
        list = insert(list, 3);


        System.out.print("Initial linked List:");
        printList(list);


        try {
            System.out.println("\nInsert '4' after third:");
            insertAfterThird(list, 4);
            System.out.println("Output:");
            printList(list);

            System.out.println("Insert '5' after third:");
            insertAfterThird(list, 5);
            System.out.println("Output:");
            printList(list);

            System.out.println("Insert '6' after third:");
            insertAfterThird(list, 6);
            System.out.println("Output:");
            printList(list);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}
Output 1: insert when linked list has more than 3 element

output 2: when linked list has less than 3 element.

list = insert(list, 3); comment this line in main method to get this output

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
To class DoublyLinkedList, add method search(E e) that receives an element e and returns the node...
To class DoublyLinkedList, add method search(E e) that receives an element e and returns the node number that has the element (assume first node is number 1), if there is no node has that element , it returns -1 java language
Exercise 1 In this exercise, you will add a method swapNodes to SinglyLinkedList class. This method...
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....
Complete the redblacktree in Java. Add a public boolean isBlack field to the Node inner class....
Complete the redblacktree in Java. Add a public boolean isBlack field to the Node inner class. Make every Node object have a false isBlack field, all new node is red by default. In the end of the insert method, set the root node of your red black tree to be black. Implement the rotate() and recolor() functions, and create tests for them in a separate class. import java.util.LinkedList; public class BinarySearchTree<T extends Comparable<T>> { protected static class Node<T> { public...
based on the code below, answer the questions Question 1: The LinkedList class uses another class...
based on the code below, answer the questions Question 1: The LinkedList class uses another class called Node (which is defined inside LinkedList.java). What are the fields in the Node class? Question 2: The Node class uses generics. Why? Question 3: The linkFirst method contains the following lines of code: if (f == null) last = newNode; else f.prev = newNode; What is the value of the linked list’s size attribute at this point in the code if f ==...
1. Design and implement a CircularLinkedList, which is essentially a linked list in which the next...
1. Design and implement a CircularLinkedList, which is essentially a linked list in which the next reference of the tail node is set to refer back to the head of the list (rather than null) . Start from the SinglyLinkedList provided in the Lecture (not the built-in Java LinkedList class). 2. Starting from  SinglyLinkedList you will need to modify or complete methods: first(), last(), addFirst(), addLast(), removeFirst(), toString(), and also create a new rotate() method which will move the tail to...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
c++ data structures linked list delete node bool deleteNode(int); pass this method an id to delete....
c++ data structures linked list delete node bool deleteNode(int); pass this method an id to delete. Return true or false to indicate success or failure. Delete the memory the node was using The algorithm for deleting a Node to a Linked List (general case): ● Begin at the head. ● Compare the id to the current node. ● If search id > current id, stop. ● Detach the current Node ○ current->previous->next = current->next ○ current->next->previous = current->previous ● Deallocate...
The main goal is to implement two recursive methods, each is built to manipulate linked data...
The main goal is to implement two recursive methods, each is built to manipulate linked data structures. To host these methods you also have to define two utterly simplified node classes. 1.) Add a class named BinaryNode to the project. This class supports the linked representation of binary trees. However, for the BinaryNode class Generic implementation not needed, the nodes will store integer values The standard methods will not be needed in this exercise except the constructor 2.) Add a...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
Lab 02, Data Abstractions and Structures, CSE 274, Fall 2019 Linked Bag In this lab, we...
Lab 02, Data Abstractions and Structures, CSE 274, Fall 2019 Linked Bag In this lab, we will implement the Linked Bag. The bag will contain a sequence of strings. First, you need to design the Node class (Node.java). It will contain an integer data and a reference to the next Node. The constructor of Node class receives an integer and assigns it to the data field. It also has a default constructor. Then we will design another class named LinkedBag...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT