Question

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 = new SLNode(a);

if (head == null) {

head = newNode;

tail = newNode;

} else {

tail.next = newNode;

tail = newNode;

}

}

public void SLswap(int i) throws illegalOperation {//i is index of node to change. method swaps specified node of index "i" with following node.

if(i>=(size()-1))

throw new illegalOperation("must swap one of the nodes, OR or you tried to swap last node... but cant do that since this method swaps node with next one");

if (size() < 2)

throw new illegalOperation("cant swap if theres less than two elements");

else if (size() == 2) {

SLNode placeholder = tail;

tail = head;

head = placeholder;

} // end else if

else if(i==0) {

SLNode anotherTemp = head.next;

SLNode temp = head.next.next;

head.next.next = head;

head.next = temp;

head = anotherTemp;

}//end else if

else {

SLNode iterationNode = head;

for (int j = 0; j<i; j++) {//order of pointing: iterationNode => iterationNode.next => nodeB(iterationNode.next.next) => tempA(iterationNode.next.next.next)... GOAL: swap iterationNode.next with nodeB(iteraitonNode.next.next)

if (j==(i-1)) {//ie: "if" condition met if the next iterationNode.next is of index i, therefore trying to swap iterationNode.next with iterationNode.next.next

SLNode tempA = iterationNode.next.next.next;

SLNode tempB = iterationNode.next.next;

iterationNode.next.next.next = iterationNode.next;

iterationNode.next.next = tempA;

iterationNode.next = tempB;

break;

}

iterationNode = iterationNode.next; //iterate to next node

} // end for-loop

}

}

public int size() {//returns number of nodes in SingleLinkedList

SLNode u = head;

int size = 0;

while (u != null) {

size++;

u = u.next;

}

return size;

}

public void display() { //prints values of all nodes in SLL, starting from head

SLNode current = head;

if(head == null) {

System.out.println("List is empty");

return;

}

System.out.println("Nodes of doubly linked list: ");

while(current != null) {

//Prints each node by incrementing the pointer.

System.out.print(current.data + " ");

current = current.next;

}

System.out.println('\n');

}

public static void main(String[] args) {

SLList myList = new SLList();

myList.add(3);

myList.add(6); //WANT TO BE ABLE TO ADD THINGS OF TYPE T!!

myList.add(1);

myList.add(4);

myList.add(2);

try {

myList.SLswap(2);

}catch(illegalOperation e) {};

myList.display();

SLList yourList = new SLList();

int numAdds = IOHelper.getInt("enter number of add calls to make: ");

int toAdd;

try {

for(int i=0; i<numAdds; i++) {

toAdd=IOHelper.getInt("enter integer to add: ");

yourList.add(toAdd);

}

int toSwap = IOHelper.getInt("enter index to swap: ");

yourList.SLswap(toSwap);} catch(illegalOperation e) {};

yourList.display();

System.out.println("DONE");

}//end main

}//end SLList

public class SLNode {

int data; //data that a node holds

SLNode next; // next node in the SSList that this given node will point to

  

public SLNode(int data) {

this.data = data;

this.next = null;

}

}

Homework Answers

Answer #1

Hello,

Below is the code required for the above problem. I noticed a couple of discrepancies which I am pointing out as well. Hope it helps.

First to let the Single Linked List use any other data as well instead of int, we have to define the node class in such a way that it takes any data as well instead of just int. I have defined it below :

//Ndde class for the single linked list
public class SLNode<T> {
    T data; //data that a node holds
    SLNode next; // next node in the SSList that this given node will point to

    public SLNode(T data) {
        this.data = data;
        this.next = null;
    }
}

The class above will take any data now instead of just int.

One thing I noticed in the SLList class,which appeared to me as an error was the use of illegalOperation. I am guessing that it is a user defined exception class designed by you or it is a part of your code as it's not available to me. If it is not, I think you would like to change the name of the class and change it to IllegalOperationException instead of just illegalOperation. It enhances the readability and keep up with good Java coding practices as well. If it's not defined by you, and you're trying to throw an exception, I would suggest you use the basic Exception class like this

throw new Exception("your message here")

instead of illegalOperation. Throwing and catching this would be much better I guess.

Below is the code for the class SLList which will take any other data as well. I haven't made any changes to IOHelper taking in int, just defined how it can use any other data to create the list as required in the question above, so I have included the main method as it is  :

public class SLList<T> {

    public SLNode head = null;
    public SLNode tail = null;

    public void add(T a) {// add() method present for testing purposes
        SLNode newNode = new SLNode(a);
        if (head == null) {
            head = newNode;
            tail = newNode;
        } else {
            tail.next = newNode;
            tail = newNode;
        }
    }

    public void SLswap(int i) throws IllegalOperation {//i is index of node to change. method swaps specified node of index "i" with following node.

        if(i>=(size()-1))
            throw new illegalOperation("must swap one of the nodes, OR or you tried to swap last node... but cant do that since this method swaps node with next one");

        if (size() < 2)
            throw new illegalOperation("cant swap if theres less than two elements");
        else if (size() == 2) {
            SLNode placeholder = tail;
            tail = head;
            head = placeholder;
        } // end else if

        else if(i==0) {
            SLNode anotherTemp = head.next;
            SLNode temp = head.next.next;
            head.next.next = head;
            head.next = temp;
            head = anotherTemp;
        }//end else if
        else {

            SLNode iterationNode = head;
            for (int j = 0; j<i; j++) {//order of pointing: iterationNode => iterationNode.next => nodeB(iterationNode.next.next) => tempA(iterationNode.next.next.next)... GOAL: swap iterationNode.next with nodeB(iteraitonNode.next.next)
                if (j==(i-1)) {//ie: "if" condition met if the next iterationNode.next is of index i, therefore trying to swap iterationNode.next with iterationNode.next.next
                    SLNode tempA = iterationNode.next.next.next;
                    SLNode tempB = iterationNode.next.next;
                    iterationNode.next.next.next = iterationNode.next;
                    iterationNode.next.next = tempA;
                    iterationNode.next = tempB;
                    break;
                }
                iterationNode = iterationNode.next; //iterate to next node
            } // end for-loop
        }
    }

    public int size() {//returns number of nodes in SingleLinkedList
        SLNode u = head;
        int size = 0;
        while (u != null) {
            size++;
            u = u.next;
        }
        return size;
    }

    public void display() { //prints values of all nodes in SLL, starting from head

        SLNode current = head;

        if(head == null) {
            System.out.println("List is empty");
            return;
        }

        System.out.println("Nodes of doubly linked list: ");
        while(current != null) {
            //Prints each node by incrementing the pointer.
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println('\n');
    }

    public static void main(String[] args) {

        SLList myList = new SLList();
        myList.add(3);
        myList.add(6); //WANT TO BE ABLE TO ADD THINGS OF TYPE T!!
        myList.add(1);
        myList.add(4);
        myList.add(2);

        try {
            myList.SLswap(2);
        }catch(illegalOperation e) {};

        myList.display();
        SLList yourList = new SLList();
        int numAdds = IOHelper.getInt("enter number of add calls to make: ");
        int toAdd;

        try {
            for(int i=0; i<numAdds; i++) {
                toAdd=IOHelper.getInt("enter integer to add: ");
                yourList.add(toAdd);
            }
            int toSwap = IOHelper.getInt("enter index to swap: ");
            yourList.SLswap(toSwap);
        } catch(illegalOperation e) {};

        yourList.display();
        System.out.println("DONE");
    }//end main

}//end SLList

I hope that helped. :)

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
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
Question: I get a Segmentation fault error sometimes when I addElementBack or print. Am I using...
Question: I get a Segmentation fault error sometimes when I addElementBack or print. Am I using pointers correctly and deleting memory properly? #ifndef DYNAMICARRAY_H #define DYNAMICARRAY_H #include <cstdlib> #include <iostream> using namespace std; // Node class class Node { int data; Node* next; Node* prev; public: Node(); Node(int); void SetData(int newData) { data = newData; }; void SetNext(Node* newNext) { next = newNext; }; void SetPrev(Node* newPrev) { prev = newPrev; }; int getData() { return data; }; Node* getNext()...
i want to complete this code to insert a new node in the middle of list...
i want to complete this code to insert a new node in the middle of list (take a node data from user, search the node and insert new node after this node). this is the code #include <iostream> #include <stdlib.h> using namespace std ; struct Node{                int data;                Node *link ;}; struct Node *head=NULL, *tail=NULL; /* pointers to Node*/ void InsertFront(); void InsertRear(); void DeleteFront(); void DeleteRear(); int main(){                int choice;                do{                               cout << "1:...
It is about C++linked list code. my assignment is making 1 function, in below circumstance,(some functions...
It is about C++linked list code. my assignment is making 1 function, in below circumstance,(some functions are suggested for easier procedure of making function.) void search_node(struct linked_list* list, int find_node_ value) (The function to make) This function finds the node from the list that value is same with find_node_value and count the order of the node. This function should print message “The order of (node_value) is (order).” and error message “Function search_node : There is no such node to search.”....
IN C++ PLEASE!!! What needs to be done is in the code itself where it is...
IN C++ PLEASE!!! What needs to be done is in the code itself where it is written TO DO List! #include<iostream> using namespace std; template<typename T> class DoubleList{​​​​​     class Node{​​​​​     public: T value; Node* next; Node* prev;         Node(T value = T(), Node* next = nullptr, Node* prev = nullptr){​​​​​             this->value = value;             this->next = next;             this->next = next;         }​​​​​     }​​​​​;     int size;     Node* head;     Node* tail; public:     DoubleList(){​​​​​         size = 0;         head = nullptr;     }​​​​​     int length(){​​​​​         return size;     }​​​​​...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is,...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is, which makes the last node instead of pointing to null point to the first. Code: class Node { int value; Node nextNode; Node(int v, Node n) { value = v; nextNode = n; } Node (int v) { this(v,null); } } class LinkedList { Node head; //head = null; LinkedList() { } int length() { Node tempPtr; int result = 0; tempPtr = head;...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is,...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is, which makes the last node instead of pointing to null point to the first. Code: class Node { int value; Node nextNode; Node(int v, Node n) { value = v; nextNode = n; } Node (int v) { this(v,null); } } class LinkedList { Node head; //head = null; LinkedList() { } int length() { Node tempPtr; int result = 0; tempPtr = head;...
Finish the code wherever it says TODO /**    * Node type for this list. Each...
Finish the code wherever it says TODO /**    * Node type for this list. Each node holds a maximum of nodeSize elements in an    * array. Empty slots are null.    */    private class Node {        /**        * Array of actual data elements.        */        // Unchecked warning unavoidable.        public E[] data = (E[]) new Comparable[nodeSize];        /**        * Link to next node.       ...
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 ==...
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT