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
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 ==...
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 {...
In this code, I build a single-linked list using a node class that has been created....
In this code, I build a single-linked list using a node class that has been created. How could I change this code to take data of type T, rather than int. (PS: ignore the fact that IOHelper.getInt won't work for the type T... ie second half of main). Here's my code right now: public class SLList { public SLNode head = null; public SLNode tail = null; public void add(int a) {// add() method present for testing purposes SLNode newNode...
C PROGRAMMING Doubly Linked List For this program you’ll implement a doubly linked list of strings....
C PROGRAMMING Doubly Linked List For this program you’ll implement a doubly linked list of strings. You must base your code on the doubly linked list implementation given in my Week 8 slides. Change the code so that instead of an ‘int’ each node stores a string (choose a suitable size). Each node should also have a next node pointer, and previous node pointer. Then write functions to implement the following linked list operations: • A printList function that prints...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>    #include <cstdlib> #include "QueueADT.h" using namespace std; // Definition of the node template <class ItemType> struct NodeType {        ItemType info;        NodeType<ItemType> *next; }; template <class ItemType> class LinkedQueueType: public QueueADT<ItemType> { public:        // Constructor        LinkedQueueType();           // Default constructor.           // Post: An empty queue has been created. queueFront = NULL;           //       queueBack = NULL;...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix it.. Can you explain to me what I am doing wrong? Warning: dlist.cc: In function 'std::ostream& operator<<(std::ostream&, dlist&)': dlist.cc:66:10: error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream&}' from expression of type 'dlist::node*' dlist.cc: In function 'dlist operator+(dlist&, dlist&)': dlist.cc:93:8: error: invalid operands of types 'dlist::node*' and 'dlist::node*' to binary 'operator+' dlist.cc:97:8: error: could not convert 'result' from 'int' to 'dlist' My code:...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT