Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CSC 2720 Lab practice 9 10/6/2017 1. Write a node class that contains at least o

ID: 3587520 • Letter: C

Question

CSC 2720 Lab practice 9 10/6/2017 1. Write a node class that contains at least one integer and a pointer of Node type. write one or two constructors for the class. One constructor will take no parameters, initializing an integer to zero, and a pointer to null, while the second constructor will take an integer and a pointer (of type Node) as parameters. 2. Write your own Linked List class, which will have functions to insert, remove,(the first node, or the head), and traverse through the whole linked list . Also write a Boolean method to test whether the linked list is empty, and one to test whether the list contains an integer. 3. You must write your own code. Do not import methods from the Java library. Hint: Create a third constructor in your node class that would look like this below: Public Node(int data){ this.data = data; this.next=next; } This takes an integer as a parameter, and the Node would contain this integer.

Explanation / Answer

Q.1)

// Node class

class Node{
   int data;
   Node next;

   //first constructor
   Node () {
       data = 0;
       next = null;
   }

   //second constructor
   Node (int item, Node n){
       data = item;
       next = n;
   }
}

Q.2)

// Linked list class

class linkedlist{
   //head of the list
   Node head;   

   static class Node{
       int data;
       Node next;

       //first constructor
       Node () {
           data = 0;
           next = null;
       }

       //second constructor
       Node (int item, Node n){
           data = item;
           next = n;
       }
   }

   //method to insert node at head
   public void insertAthead(int new_data){
       // allocate space for node and initialize with given data
       Node new_node = new Node(new_data, null);

       //point next of new node to head
       new_node.next = head;

       //make head of linked list to point to new node
       head = new_node;
   }

   //method to remove first node
   public void deleteFirstNode(){
       //if there are no nodes
       if(head == null)
           return;
      
       //point the head to next node
       head = head.next;
       return;
   }

   //method to traverse through linked list
   public void Traverse(){
   Node t_node = head;
   while (t_node != null){
       System.out.print(t_node.data+ " ");
       t_node = t_node.next;
   }
   }

   //Boolean function to test if list is empty
   public void boolean isEmpty(){
       Node temp = head;
       int count = 0;
       while(temp != null){
           count++;
           temp = temp.next;
       }
       if(count == 0)
           return true;
       else
           return false;
   }
}